EExcel 丞燕快速查詢2

EExcel 丞燕快速查詢2
EExcel 丞燕快速查詢2 https://sandk.ffbizs.com/
顯示具有 OpenID 標籤的文章。 顯示所有文章
顯示具有 OpenID 標籤的文章。 顯示所有文章

Ory Hydra Authorization Code Exchange => access token Use openid-client

https://github.com/panva/node-openid-client/tree/v2.x

Important! WARNING: Node.js 12 or higher is required for openid-client@3 and above. For older Node.js versions use openid-client@2.


So watch https://github.com/panva/node-openid-client/tree/v2.x

node.js package use "openid-client": "2.5.0",

client.authorizationCallback have bug, nonce mismatch always have this error even see https://github.com/panva/node-openid-client/issues/150


Correct way


https://github.com/panva/node-openid-client/blob/f1b4282ac50f7e15fc195f66bf76409af4ec4b6b/lib/client.js

see if (params.code) { Can know use grant

https://github.com/panva/node-openid-client/tree/v2.x#custom-token-endpoint-grants



      const hydraconfig= {
        "oidurl": "https://openid.hydra:9001",
        "redirectUri": "https://t.tt:9010/callback",
        "clientid": "auth-code-client",
        "clientsecretid": "secret"
      }

      //openid-client================
      const { Issuer } = require('openid-client')
      
      const hydraIssuer = await Issuer.discover(hydraconfig.oidurl) // => Promise
      .then(function (hydradiscoverIssuer) {
        console.log('Discovered issuer %s %O', hydradiscoverIssuer.issuer, hydradiscoverIssuer.metadata);
        return hydradiscoverIssuer
      });

      const client = new hydraIssuer.Client({
        client_id: hydraconfig.clientid,
        client_secret: hydraconfig.clientsecretid
      });
      
      var tokenset = await client.grant({
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: hydraconfig.redirectUri,
        code_verifier: '', //No value, because real use in Hydra login-consent. Not use client.authorizationUrl or client.authorizationPost
      });
      console.log(tokenset)

Ory Hydra Authorization Code Exchange => access token

Before posts about Hydra get access token is use golang HydraOauthConfig.Exchange(ctx, code). This is easy way. But on front website like vue or other framework how to get access token.

Use REST Client to test



POST https://openid.hydra:9001/oauth2/token
Authorization: Basic YXV0aC1jb2RlLWNsaWVudDpzZWNyZXQ=
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=cuNw76aEuckIJJyVssk2LJvqdLXffT-8Kx1s0tYFt6Y.v0Dxc2_yT9ga8c2moKx0fDbwRFVgwryAt5BJM7lOJlM
#&redirect_uri=https://certfront/oid/test/callback
#&scope=openid,offline
#&client_id=auth-code-client
#&code_verifier=
#&state=gczxkznmjkrksgytsemvwgkf

Import is: Authorization: Basic


https://github.com/ory/hydra/issues/631

Not Authorization: Bearer


base64(urlencode(client_id):urlencode(client_secret))


YXV0aC1jb2RlLWNsaWVudDpzZWNyZXQ= => auth-code-client:secret


code is callback code. When you login-consent finish step then callback to your set callback URL. Watch URL inside have code=


example: https://t.tt:9010/callback?code=cuNw76aEuckIJJyVssk2LJvqdLXffT-8Kx1s0tYFt6Y.v0Dxc2_yT9ga8c2moKx0fDbwRFVgwryAt5BJM7lOJlM&scope=openid%20offline&state=gczxkznmjkrksgytsemvwgkf

If code have error message, you need check before any step have incorrect.


In Ory Hydra get access token is not like sdk document


https://www.ory.sh/docs/hydra/sdk/api#the-oauth-20-token-endpoint

You need to sure grant_type=authorization_code Not other options.

But SDK Document No any options example. Only suggestion you use lib. So you need to try many.

like follow
https://www.oauth.com/oauth2-servers/pkce/authorization-code-exchange/
https://community.ory.sh/t/how-configure-grant-implicit-flow/411/14
https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce
https://github.com/oauthjs/express-oauth-server/issues/55
https://www.jianshu.com/p/5cf2b7a45b75
http://www.passportjs.org/docs/oauth/

Then try out a ways.

OK. Mark is not important Required.


#&redirect_uri=https://certfront/oid/test/callback
#&scope=openid,offline
#&client_id=auth-code-client
#&code_verifier=
#&state=gczxkznmjkrksgytsemvwgkf

[轉]如何使用 OpenSSL 建立開發測試用途的自簽憑證 (Self-Signed Certificate)

https://blog.miniasp.com/post/2019/02/25/Creating-Self-signed-Certificate-using-OpenSSL



目前這個方式比較靠普


建立 ssl.conf 設定檔


[req]
prompt = no
default_md = sha256
default_bits = 2048
distinguished_name = dn
x509_extensions = v3_req

[dn]
C = TW
ST = Taiwan
L = Taipei
O = Duotify Inc.
OU = IT Department
emailAddress = admin@example.com
CN = localhost

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.localhost
DNS.2 = localhost
DNS.3 = 192.168.2.100


openssl req -x509 -new -nodes -sha256 -utf8 -days 3650 -newkey rsa:2048 -keyout server.key -out server.crt -config ssl.conf

OpenID hydra docker-compose hydra-login-consent-node mariadb


docker-compose


version: '3.3'

services:
  ory-hydra-postgres:
    image: postgres:9.6
    #restart: always
    environment:
      - POSTGRES_USER=hydra
      - POSTGRES_PASSWORD=secret
      - POSTGRES_DB=hydra
    volumes:
      - hydradata:/var/lib/postgresql/data:rw
    networks:
      - openid
  # 第一次執行postgres要做資料庫格式建立 PS: network依佈屬環境為主 docker network ls 確認
  # docker run -it --rm \
  #   --network openid \
  #   oryd/hydra:latest \
  #   migrate sql --yes postgres://hydra:secret@ory-hydra-postgres:5432/hydra?sslmode=disable
  
  ory-hydra:
    image: oryd/hydra:latest
    restart: unless-stopped
    ports:
      - "9001:4444"
      - "9002:4445"
    environment:
      - SECRETS_SYSTEM=this_needs_to_be_the_same_a
      - DSN=postgres://hydra:secret@ory-hydra-postgres:5432/hydra?sslmode=disable
      - URLS_SELF_ISSUER=https://openid.hydra:9001/
      - URLS_CONSENT=http://192.168.99.100:9020/consent
      - URLS_LOGIN=http://192.168.99.100:9020/login
      - LOG_LEVEL=debug
      - OAUTH2_EXPOSE_INTERNAL_ERRORS=true
      - SERVE_PUBLIC_CORS_ENABLED=true
      - SERVE_PUBLIC_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE
      - SERVE_ADMIN_CORS_ENABLED=true
      - SERVE_ADMIN_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE
      - SERVE_TLS_KEY_BASE64=LS0tLS1CRUdJTiBFQyBQQVJBTUVURVJTLS0tLS0KQmdVcmdRUUFJZz09Ci0tLS0tRU5EIEVDIFBBUkFNRVRFUlMtLS0tLQotLS0tLUJFR0lOIEVDIFBS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2RabGxFbmFUUVBzMndyQ0JNbGpPdW80R0t6UXpHU2lScE5oU3ZPRW5Xa2x6SjlxTlFNRTR3SFFZRApWUjBPQkJZRUZHK3Z6ZkIxYmVnM1VadEpYRXZWOWRNa1hvNmdNQjhHQTFVZEl3UVlNQmFBRkcrdnpmQjFiZWczClVadEpYRXZWOWRNa1hvNmdNQXdHQTFVZEV3UUZNQU1CQWY4d0NnWUlLb1pJemowRUF3SURhUUF3WmdJeEFMUHYKODZFSFRUVElLcEJHdlQrY2NWN3djSC84SFIrc2xhZC9ZUFhLUlZwd2RDbzUyZVRPV3BDS2dGamtHNEJhd1FJeApBTGxGZFgwbEk2ZzhXS3lhRTVmKzJGZEkxYWVqQ0Ftd0xPTTZTRFJhNFVHbitDa2VwOEljeG1CTDIvQmUzSVZ6CjhnPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    networks:
      - openid


# 快速建立 auth-doce-client PS: network依佈屬環境為主 docker network ls 確認
#docker run --rm -it \
#  -e HYDRA_ADMIN_URL=https://ory-hydra:4445 \
#  --network openid \
#  oryd/hydra:latest \
#  clients create --skip-tls-verify \
#    --id auth-code-client \
#    --secret secret \
#    --grant-types authorization_code,refresh_token \
#    --response-types code,id_token,token \
#    --scope openid,offline,photos.read \
#    --callbacks https://t.tt:9010/callback

  ory-hydra-login-consent:
    #image: oryd/hydra-login-consent-node:latest
    build:
      context: hydra-login-consent-node/
    restart: unless-stopped
    ports:
      - "9020:3000"
    environment:
      - HYDRA_ADMIN_URL=https://ory-hydra:4445
      - NODE_TLS_REJECT_UNAUTHORIZED=0
    volumes:
      - hydraloginconsent:/usr/src/app:rw
    depends_on:
      - mariadb
    networks:
      - openid
  
  mariadb:
    image: mariadb:10.4.6
    #restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=secret
      - MYSQL_DATABASE=openid
    command: ['--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci']
    #第一次使執行db_init_sql.txt
    networks:
      - openid

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080
    depends_on:
      - mariadb
    networks:
      - openid

volumes:  
  hydradata: 
  hydraloginconsent:
    
networks:
  openid:
    driver: bridge


Use adminer test maraidb: http://192.168.99.100:8080 root/secret


mariadb init


DROP DATABASE IF EXISTS `openid`;
CREATE DATABASE `openid` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
USE `openid`;

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` text COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `user` (`id`, `name`, `email`, `password`) VALUES
(1, 'foobar', 'foo@bar.com', '3858f62230ac3c915f300c664312c63f');

ory-hydra-login-consent modify package.json add


"md5": "^2.2.1",
"mysql": "^2.17.1"

ory-hydra-login-consent add db/database.js


var mysql = require('mysql');

var pool = mysql.createPool({
  host     : 'mariadb',
  user     : 'root',
  password : 'secret',
  database: 'openid'
});

var query=function(sql,options,callback){  
  pool.getConnection(function(err,conn){  
    pool.query
    if(err){  
      callback(err,null,null);  
    }else{  
      conn.query(sql,options,function(err,results,fields){  
        //释放连接  
        conn.release();  
        //事件驱动回调  
        callback(err,results,fields);  
      });  
    }  
  });  
}; 

module.exports = {query, pool}

ory-hydra-login-consent modify routes/login.js


...

router.post('/', csrfProtection, function (req, res, next) {
  // The challenge is now a hidden input field, so let's take it from the request body instead
  var challenge = req.body.challenge;

  var sql = "select count(*) as count from user where email = ? and password = ?"
  var params = [req.body.email, md5(req.body.password)]
  //db.get(sql, params, (err, row) => {
  pool.query(sql, params, (err, row) => {
    if (err) {
      res.status(400).json({"db error":err.message});
      return;
    }

    if(!(row.count==1)){ //找不到
      res.render('login', {
        csrfToken: req.csrfToken(),
  
        challenge: challenge,
  
        error: 'The username / password combination is not correct'
      });
      return;
    }

    hydra.acceptLoginRequest(challenge, {
      // Subject is an alias for user ID. A subject can be a random string, a UUID, an email address, ....
      subject: req.body.email,
  
      // This tells hydra to remember the browser and automatically authenticate the user in future requests. This will
      // set the "skip" parameter in the other route to true on subsequent requests!
      remember: Boolean(req.body.remember),
  
      // When the session expires, in seconds. Set this to 0 so it will never expire.
      remember_for: 3600,
  
      // Sets which "level" (e.g. 2-factor authentication) of authentication the user has. The value is really arbitrary
      // and optional. In the context of OpenID Connect, a value of 0 indicates the lowest authorization level.
      // acr: '0',
    })
    .then(function (response) {
      // All we need to do now is to redirect the user back to hydra!
      res.redirect(response.redirect_to);
    })
    // This will handle any error that happens when making HTTP calls to hydra
    .catch(function (error) {
      next(error);
    });

  });

  // Let's check if the user provided valid credentials. Of course, you'd use a database or some third-party service
  // for this!
  // if (!(req.body.email === 'foo@bar.com' && req.body.password === 'foobar')) {
  //   // Looks like the user provided invalid credentials, let's show the ui again...

  //   res.render('login', {
  //     csrfToken: req.csrfToken(),

  //     challenge: challenge,

  //     error: 'The username / password combination is not correct'
  //   });
  //   return;
  // }

  // Seems like the user authenticated! Let's tell hydra...
  // hydra.acceptLoginRequest(challenge, {
  //   // Subject is an alias for user ID. A subject can be a random string, a UUID, an email address, ....
  //   subject: 'foo@bar.com',

  //   // This tells hydra to remember the browser and automatically authenticate the user in future requests. This will
  //   // set the "skip" parameter in the other route to true on subsequent requests!
  //   remember: Boolean(req.body.remember),

  //   // When the session expires, in seconds. Set this to 0 so it will never expire.
  //   remember_for: 3600,

  //   // Sets which "level" (e.g. 2-factor authentication) of authentication the user has. The value is really arbitrary
  //   // and optional. In the context of OpenID Connect, a value of 0 indicates the lowest authorization level.
  //   // acr: '0',
  // })
  //   .then(function (response) {
  //     // All we need to do now is to redirect the user back to hydra!
  //     res.redirect(response.redirect_to);
  //   })
  //   // This will handle any error that happens when making HTTP calls to hydra
  //   .catch(function (error) {
  //     next(error);
  //   });

  // You could also deny the login request which tells hydra that no one authenticated!
  // hydra.rejectLoginRequest(challenge, {
  //   error: 'invalid_request',
  //   error_description: 'The user did something stupid...'
  // })
  //   .then(function (response) {
  //     // All we need to do now is to redirect the browser back to hydra!
  //     res.redirect(response.redirect_to);
  //   })
  //   // This will handle any error that happens when making HTTP calls to hydra
  //   .catch(function (error) {
  //     next(error);
  //   });
});

https://t.tt:9010 When login id/pwd, can use adminer change database user email/password.

OpenID hydra docker-compose


docker-compose

version: '3.3'

services:
  ory-hydra-postgres:
    image: postgres:9.6
    #restart: always
    environment:
      - POSTGRES_USER=hydra
      - POSTGRES_PASSWORD=secret
      - POSTGRES_DB=hydra
    volumes:
      - hydradata:/var/lib/postgresql/data:rw
    networks:
      - openid

# 第一次執行postgres要做資料庫格式建立 PS: network依佈屬環境為主 docker network ls 確認
# docker run -it --rm \
#   --network openid \
#   oryd/hydra:latest \
#   migrate sql --yes postgres://hydra:secret@ory-hydra-postgres:5432/hydra?sslmode=disable

  ory-hydra:
    image: oryd/hydra:latest
    restart: unless-stopped
    ports:
      - "9001:4444"
      - "9002:4445"
    environment:
      - SECRETS_SYSTEM=this_needs_to_be_the_same_a
      - DSN=postgres://hydra:secret@ory-hydra-postgres:5432/hydra?sslmode=disable
      - URLS_SELF_ISSUER=https://openid.hydra:9001/
      - URLS_CONSENT=http://192.168.99.100:9020/consent
      - URLS_LOGIN=http://192.168.99.100:9020/login
      - LOG_LEVEL=debug
      - OAUTH2_EXPOSE_INTERNAL_ERRORS=true
      - SERVE_PUBLIC_CORS_ENABLED=true
      - SERVE_PUBLIC_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE
      - SERVE_ADMIN_CORS_ENABLED=true
      - SERVE_ADMIN_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE
      - SERVE_TLS_KEY_BASE64=LS0tLS1CRUdJTiBFQyBQQVJBTUVURVJTLS0tLS0KQmdVcmdRUUFJZz09Ci0tLS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lmaDVCdnA5alBNQlArN0FqU1V2dWdXSU5jTHNJRXBsOU8KcnNRcmZFN2RabGxFbmFUUVBzMndyQ0JNbGpPdW80R0t6UXpHU2lScE5oU3ZPRW5Xa2x6SjlxTlFNRTR3SFFZRApWUjBPQkJZRUZHK3Z6ZkIxYmVnM1VadEpYRXZWOWRNa1hvNmdNQjhHQTFVZEl3UVlNQmFBRkcrdnpmQjFiZWczClVadEpYRXZWOWRNa1hvNmdNQXdHQTFVZEV3UUZNQU1CQWY4d0NnWUlLb1pJemowRUF3SURhUUF3WmdJeEFMUHYKODZFSFRUVElLcEJHdlQrY2NWN3djSC84SFIrc2xhZC9ZUFhLUlZwd2RDbzUyZVRPV3BDS2dGamtHNEJhd1FJeApBTGxGZFgwbEk2ZzhXS3lhRTVmKzJGZEkxYWVqQ0Ftd0xPTTZTRFJhNFVHbitDa2VwOEljeG1CTDIvQmUzSVZ6CjhnPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    networks:
      - openid
    #這行非常重要,docker成功運行後,要進geht console執行 admin.addPeer("enode://444a16729d32431bbdaa594272e3509cdeaaf3c995ffb583589163d35f8b36ad14394ab037ac186525f579700e6500cacfb1f953fdf066fa05da0e1d409f7f79@140.110.18.199:30301")

  ory-hydra-login-consent:
    #image: oryd/hydra-login-consent-node:latest
    build:
      context: hydra-login-consent-node/
    restart: unless-stopped
    ports:
      - "9020:3000"
    environment:
      - HYDRA_ADMIN_URL=https://ory-hydra:4445
      - NODE_TLS_REJECT_UNAUTHORIZED=0
    volumes:
      - hydraloginconsent:/usr/src/app:rw
    networks:
      - openid

# 快速建立 auth-doce-client PS: network依佈屬環境為主 docker network ls 確認
#docker run --rm -it \
#  -e HYDRA_ADMIN_URL=https://ory-hydra:4445 \
#  --network openid \
#  oryd/hydra:latest \
#  clients create --skip-tls-verify \
#    --id auth-code-client \
#    --secret secret \
#    --grant-types authorization_code,refresh_token \
#    --response-types code,id_token,token \
#    --scope openid,offline,photos.read \
#    --callbacks https://t.tt:9010/callback

volumes:  
  hydradata: 
  hydraloginconsent:
    
networks:
  openid:
    driver: bridge

ory-hydra-login-consent download

https://github.com/ory/hydra-login-consent-node
Directory name is hydra-login-consent-node


go run main.go

https://sueboy.blogspot.com/2019/06/openid-hydra-cant-finish-error.html


Broswer https://t.tt:9010

nightwatch OpenID Hydra Windows

Windows

Update chrome v75



> mkdir t
> cd t
> midir tests

> npm install nightwatch  --save-dev
> npm install chromedriver --save-dev

> nano nightwatch.js
require('nightwatch/bin/runner.js');

> nano nightwatch.conf.js
const chrome = require('chromedriver')

module.exports = {
  src_folders: ['tests'],
  webdriver: {
    start_process: true,
    server_path: chrome.path,
    port: 9515,
  },
  test_settings: {
    default: {
      desiredCapabilities: {
        browserName: 'chrome',
      },
    },
  },
}

> nano tests/test.js
module.exports = {
  'step one: navigate to google' : function (browser) {
    for (var i = 0; i < 10; i += 1) {
      browser
        .url('https://t.tt:9010')
        .waitForElementVisible('body', 1000)
        .click('a')
        .waitForElementVisible('input[type=email]')
        .setValue('input[type=email]', 'foo@bar.com')
        .setValue('input[type=password]', 'foobar')
        .click('input[type=submit]', function(result) {
          this.assert.strictEqual(result.status, 0);
        })
        .waitForElementVisible('input[type=checkbox]')
        .click('input[id=openid]')
        .click('input[id=offline]')
        .click('input[id=accept]', function(result) {
          this.assert.strictEqual(result.status, 0);
        })
    }
  },
};

> node nightwatch.js tests/test.js

OpenID Hydra session data can't show at userinfo or introspect

If you use consent website(official login&consent) run all step, routes/consent.js session part need remove mark, surely you can get session data.





@token= xLPcJ3tobDqGUDxIVTxWt2p7w_odZSV22IAlUf5QPZU.YD6R_xKQ2ldCLbEV7mmc01E6ZLzemzdEC5H4-otTMPg

### userinfo
GET https://openid.hydra:9001/userinfo
Authorization: Bearer {{token}}

### introspect
POST https://openid.hydra:9002/oauth2/introspect
Content-Type: application/x-www-form-urlencoded

token={{token}}
&scope=openid+photos.read

PS:&scope=openid+photos.read can remove.

But you use REST Client need fix. Put session data by yourself.



### accept conent scope
PUT https://192.168.99.100:9002/oauth2/auth/requests/consent/accept?consent_challenge={{consent_challenge}}
Content-Type: application/json

{
  "grant_scope": ["openid", "photos.read"],
  "session": {
    "access_token": { "foo": "bar" },
    "id_token": { "baz": "bar" }
  }
}

Try and watch many document. Can't get real why. Official Website no any discuss.



OpenID hydra

https://www.ory.sh/docs/next/hydra/oauth2#oauth-20-scope

A OAuth 2.0 Scope is not a permission:

A permission allows an actor to perform a certain action in a system: Bob is allowed to delete his own photos.
OAuth 2.0 Scope implies that an end-user granted certain privileges to a client: Bob allowed the OAuth 2.0 Client to delete all users.
The OAuth 2.0 Scope can be granted without the end-user actually having the right permissions. In the examples above, Bob granted an OAuth 2.0 Client the permission ("scope") to delete all users in his name. However, since Bob is not an administrator, that permission ("access control") is not actually granted to Bob. Therefore any request by the OAuth 2.0 Client that tries to delete users on behalf of Bob should fail.


我授權程式可以“讀取、刪除“權限,但實際上授權程式能不能真正“讀取、刪除“資料 或是 真正有“讀取、刪除“權限 是不一定有的

OpenID hydra context data save

hydra login consent node
https://github.com/ory/hydra-login-consent-node

When login success, context data be saved .
Can use
GET https://openid.hydra:9002/oauth2/auth/sessions/consent?subject=foo@bar.com HTTP/1.1
check by subject.

routes/login.js



hydra.acceptLoginRequest(challenge, {

    context: {
      "test1": "test1",
      "test2": { "test2i": "test2i"}
    },

Database keep context

Table name: hydra_oauth2_consent_request save context data. Here is Postgresql (pg).



===== Postgresql command ====

1. Login Postgresql (pg) docker

2.

psql hydra -U hydra

#login pg (already in db cmd)
\dt;
select * from hydra_oauth2_consent_request;


=============== userinfo ===============

GET https://openid.hydra:9001/userinfo
Authorization: Bearer pFmYrUWtkGswx6RjvsGfgUAl4gV88id90P7hVLHUfQ4.AhbkWRawXV35S_V6Nq-Hf3DlBZ8Dl622sB4M3dg_hNQ

{
  "sid": "891db392-859c-49d9-958c-83135f6986ee",
  "sub": "foo@bar.com"
}

sid can check by use sub.

GET https://openid.hydra:9002/oauth2/auth/sessions/consent?subject=foo@bar.com HTTP/1.1

OpenID hydra docker-compose STOP

https://github.com/ory/examples/blob/master/full-stack/docker-compose.yml


Maybe use 5 min quickstart.yml better.

OpenID hydra SSL problem Finish!


1、use docker-machine create vm get ip: 192.168.99.100

2、deploy
https://www.ory.sh/docs/next/hydra/configure-deploy


docker network create hydraguide



docker run \
  --network hydraguide \
  --name ory-hydra-example--postgres \
  -e POSTGRES_USER=hydra \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=hydra \
  -d postgres:9.6



export SECRETS_SYSTEM=this_needs_to_be_the_same_always_and_also_very_$3cuR3-._

export DSN=postgres://hydra:secret@ory-hydra-example--postgres:5432/hydra?sslmode=disable

docker pull oryd/hydra:latest



docker run -it --rm \
  --network hydraguide \
  oryd/hydra:latest \
  migrate sql --yes $DSN

=====creat ssl cert and key====
!!注意!! 產生方式改用 https://sueboy.blogspot.com/2019/08/openssl-self-signed-certificate.html 較為保險,不容易發生 ERR_SSL_VERSION_OR_CIPHER_MISMATCH 錯誤!

create two cert. 1. t.tt 2. openid.hydra



In vm
openssl genrsa -out t.tt.key 2048
openssl ecparam -genkey -name secp384r1 -out t.tt.key
openssl req -new -x509 -sha256 -key t.tt.key -out t.tt.crt -days 3650
Important!! t.tt.crt step: Common Name (e.g. server FQDN or YOUR name) []: t.tt


openssl genrsa -out openid.hydra.key 2048
openssl ecparam -genkey -name secp384r1 -out openid.hydra.key
openssl req -new -x509 -sha256 -key openid.hydra.key -out openid.hydra.crt -days 3650
Important!! openid.hydra.crt step: Common Name (e.g. server FQDN or YOUR name) []: openid.hydra

Use openid.hydra.key and openid.hydra.crt to base64 code
https://www.base64encode.org/

openid.hydra.key

-----BEGIN EC PARAMETERS-----
BgUrgQQAIg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDCKnGgVqIW7YinbQeyPGyQ44Gu6UQDzU9HCKb33MifxRXE0dnu6+7Zu
0tBTqHPDuLygBwYFK4EEACKhZANiAARnx56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CdnA5alBNQlArN0FqU1V2dWdXSU5jTHNJRXBsOU8KcnNRcmZFN2RabGxFbmFUUVBzMndyQ0JNbGpPdW80R0t6UXpHU2lScE5oU3ZPRW5Xa2x6SjlxTlFNRTR3SFFZRApWUjBPQkJZRUZHK3Z6ZkIxYmVnM1VadEpYRXZWOWRNa1hvNmdNQjhHQTFVZEl3UVlNQmFBRkcrdnpmQjFiZWczClVadEpYRXZWOWRNa1hvNmdNQXdHQTFVZEV3UUZNQU1CQWY4d0NnWUlLb1pJemowRUF3SURhUUF3WmdJeEFMUHYKODZFSFRUVElLcEJHdlQrY2NWN3djSC84SFIrc2xhZC9ZUFhLUlZwd2RDbzUyZVRPV3BDS2dGamtHNEJhd1FJeApBTGxGZFgwbEk2ZzhXS3lhRTVmKzJGZEkxYWVqQ0Ftd0xPTTZTRFJhNFVHbitDa2VwOEljeG1CTDIvQmUzSVZ6CjhnPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=


docker run -d \
  --name ory-hydra-example--hydra \
  --network hydraguide \
  -p 9001:4444 \
  -p 9002:4445 \
  -e SECRETS_SYSTEM=$SECRETS_SYSTEM \
  -e DSN=$DSN \
  -e URLS_SELF_ISSUER=https://openid.hydra:9001/ \
  -e URLS_CONSENT=http://192.168.99.100:9020/consent \
  -e URLS_LOGIN=http://192.168.99.100:9020/login \
  -e LOG_LEVEL=debug \
  -e OAUTH2_EXPOSE_INTERNAL_ERRORS=1 \
  -e SERVE_PUBLIC_CORS_ENABLED=true \
  -e SERVE_PUBLIC_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE \
  -e SERVE_ADMIN_CORS_ENABLED=true \
  -e SERVE_ADMIN_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE \
  -e SERVE_TLS_KEY_BASE64=LS0tLS1CRUdJTiBFQyBQQVJBTUVURVJTLS0tLS0KQmdVcmdRUUFJZz09Ci0tLS0tRU5EIEVDIFBBUkFNRVRFUlMtLS0tLQotLS0tLUJFR0l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8KcnNRcmZFN2RabGxFbmFUUVBzMndyQ0JNbGpPdW80R0t6UXpHU2lScE5oU3ZPRW5Xa2x6SjlxTlFNRTR3SFFZRApWUjBPQkJZRUZHK3Z6ZkIxYmVnM1VadEpYRXZWOWRNa1hvNmdNQjhHQTFVZEl3UVlNQmFBRkcrdnpmQjFiZWczClVadEpYRXZWOWRNa1hvNmdNQXdHQTFVZEV3UUZNQU1CQWY4d0NnWUlLb1pJemowRUF3SURhUUF3WmdJeEFMUHYKODZFSFRUVElLcEJHdlQrY2NWN3djSC84SFIrc2xhZC9ZUFhLUlZwd2RDbzUyZVRPV3BDS2dGamtHNEJhd1FJeApBTGxGZFgwbEk2ZzhXS3lhRTVmKzJGZEkxYWVqQ0Ftd0xPTTZTRFJhNFVHbitDa2VwOEljeG1CTDIvQmUzSVZ6CjhnPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo= \
  oryd/hydra:latest serve all
LOG_LEVEL ~ SERVE_ADMIN_CORS_ALLOWED_METHODS not important, add by yourself.



docker run -d \
  --name ory-hydra-example--consent \
  -p 9020:3000 \
  --network hydraguide \
  -e HYDRA_ADMIN_URL=https://ory-hydra-example--hydra:4445 \
  -e NODE_TLS_REJECT_UNAUTHORIZED=0 \
  oryd/hydra-login-consent-node:latest



docker run --rm -it \
  -e HYDRA_ADMIN_URL=https://ory-hydra-example--hydra:4445 \
  --network hydraguide \
  oryd/hydra:latest \
  clients create --skip-tls-verify \
    --id auth-code-client \
    --secret secret \
    --grant-types authorization_code,refresh_token \
    --response-types token,code,id_token \
    --scope openid,offline,photos.read \
    --callbacks https://t.tt:9010/callback
This step is different quickstart.yml. Use https and t.tt domain. quickstart.yml start serve --dangerous-force-http
All become http. So last step can callback use http. This production way only use https. And token user only http. So use self OpenID client.


1. nano /etc/hosts or windows hosts

127.0.0.1 t.tt

192.168.99.100 openid.hydra


2. use golang OpenID client + ssl

https://blog.csdn.net/wangshubo1989/article/details/77980316
https://github.com/denji/golang-tls


copy t.tt.key and t.tt.crt to go project



main.go


package main

import (
 "context"
 "crypto/tls"
 "fmt"
 "log"
 "net/http"
 "strings"

 "golang.org/x/oauth2"
)

const htmlIndex = `
<html><body>
<a href="/HydraLogin">Log in with Hydra</a>
</body></html>
`
var endpotin = oauth2.Endpoint{
 AuthURL:  "https://openid.hydra:9001/oauth2/auth",
 TokenURL: "https://openid.hydra:9001/oauth2/token",
}

var HydraOauthConfig = &oauth2.Config{
 ClientID:     "auth-code-client",
 ClientSecret: "secret",
 RedirectURL:  "https://t.tt:9010/callback",
 Scopes:       []string{"openid", "offline", "photos.read"},
 Endpoint:     endpotin,
}

const oauthStateString = "gczxkznmjkrksgytsemvwgkf"

func main() {
 http.HandleFunc("/", handleMain)
 http.HandleFunc("/HydraLogin", handleHydraLogin)
 http.HandleFunc("/callback", handleCallback)
 //fmt.Println(http.ListenAndServe(":9010", nil))
 err := http.ListenAndServeTLS(":9010", "t.tt.crt", "t.tt.key", nil)
 if err != nil {
  log.Fatal("ListenAndServe: ", err)
 }
}

func handleMain(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, htmlIndex)
}

func handleHydraLogin(w http.ResponseWriter, r *http.Request) {
 url := HydraOauthConfig.AuthCodeURL(oauthStateString)
 log.Println(url)
 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

func handleCallback(w http.ResponseWriter, r *http.Request) {
 // add transport for self-signed certificate to context
 tr := &http.Transport{
  TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
 }
 sslcli := &http.Client{Transport: tr}
 ctx := context.TODO()
 ctx = context.WithValue(ctx, oauth2.HTTPClient, sslcli)

 state := r.FormValue("state")
 if state != oauthStateString {
  log.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
  http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  return
 }
 log.Println("state:", state)

 code := r.FormValue("code")
 log.Println("code: ", code)
 token, err := HydraOauthConfig.Exchange(ctx, code)
 if err != nil {
  log.Println("Code exchange failed with:", err)
  http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  return
 }

 TokenMsg := "<p>Token Info</p>"
 TokenMsg += fmt.Sprintf("token.AccessToken : %s \n", token.AccessToken)
 TokenMsg += fmt.Sprintf("token.TokenType : %s \n", token.TokenType)
 TokenMsg += fmt.Sprintf("token.RefreshToken : %s \n", token.RefreshToken)
 TokenMsg += fmt.Sprintf("token.Expiry : %s \n", token.Expiry)
 TokenMsg += fmt.Sprintf("token Exra id_token : %s \n", token.Extra("id_token"))
 TokenMsg += fmt.Sprintf("token Exra scope : %s \n", token.Extra("scope"))

 log.Println(TokenMsg)

 log.Println("===========all token==========")
 log.Println("token: ", token)

 log.Println("Authentication token.... ")
 client := HydraOauthConfig.Client(ctx, token)
 resp, err := client.Get("https://openid.hydra:9001/")
 if err != nil {
  log.Println(err)
 } else {
  log.Println("Authentication successful !!")
 }
 defer resp.Body.Close()

 // show succes page
 msg := "<p><strong>Success!</strong></p>"
 msg += "<p>You are authenticated and can now return to the CLI.</p>"
 msg += strings.ReplaceAll(TokenMsg, "\n", "<p>")

 fmt.Fprintf(w, msg)

 //response, err := http.Get("https://openid.hydra:9001/userinfo?access_token=" + token.AccessToken)
 //defer response.Body.Close()
 //contents, err := ioutil.ReadAll(response.Body)
 //fmt.Fprintf(w, "Content: %s\n", contents)
}


Try https://t.tt Now can run finish all step.



hydra.rest

###
@audience = audience=
@max_age = max_age=0
@nonce = nonce=kwhqocyluutsstfouosxluqc
@prompt = prompt=

@response_type = response_type=code
@state = state=gczxkznmjkrksgytsemvwgkf

@client_id = client_id=auth-code-client
@scope = scope=openid+offline+photos.read
@redirect_url = redirect_url=https%3A%2F%2Ft.tt%3A9010%2Fcallback

@auth-tailpart = {{audience}}&{{max_age}}&{{nonce}}&{{prompt}}
@9001_auth = https://openid.hydra:9001/oauth2/auth?

### get hydra login page
Get {{9001_auth}}&{{client_id}}&{{redirect_url}}&{{scope}}&{{response_type}}&{{state}}&{{auth-tailpart}}

###
//提醒:csrf可以不更新,challenge一定要更新
@9020_login = http://192.168.99.100:9020/login
@9020_consent = http://192.168.99.100:9020/consent
@_csrf1 = Gxa6Hip4-J_A3L2kpRc72Iclw_Ql8eIcQiTc
@login_challenge = bc55b64985f1400b90a2c2741f8780f2
@email = foo@bar.com
@password = foobar

### get login
GET https://192.168.99.100:9002/oauth2/auth/requests/login?login_challenge={{login_challenge}}

### login
#POST {{9020_login}}
#Content-Type: application/x-www-form-urlencoded

#_csrf={{_csrf1}}
#&challenge={{login_challenge}}
#&email={{email}}
#&password={{password}}

### accept login
PUT https://192.168.99.100:9002/oauth2/auth/requests/login/accept?login_challenge={{login_challenge}}
Content-Type: application/json

{
  "subject": "foo@bar.com",
  "remember": false,
  "remember_for": 3600
}

@login_verifier = login_verifier=1025ccb8109047668715c8162459d6de

### get conent
GET {{9001_auth}}{{login_verifier}}&{{client_id}}&{{redirect_url}}&{{scope}}&{{response_type}}&{{state}}&{{auth-tailpart}}

###
@consent_challenge = d23b6822d88842078a0d83677e8709a8
@_csrf2 = PLSPrz8R-GqmzKwgMtNus3LiX-p9Oh0QaLnQ

### requests consent
###GET {{9020_consent}}?consent_challenge={{consent_challenge}}


### get conent scope
GET https://192.168.99.100:9002/oauth2/auth/requests/consent?consent_challenge={{consent_challenge}}

@submit = Allow access

### accept conent scope
PUT https://192.168.99.100:9002/oauth2/auth/requests/consent/accept?consent_challenge={{consent_challenge}}
Content-Type: application/json

{
  "grant_scope": ["openid", "photos.read"],
  "session": {
    "access_token": { "foo": "bar" },
    "id_token": { "baz": "bar" }
  }
}

@consent_verifier = consent_verifier=ed04b20447c343338e9000b2db640f3c
### get auth token
GET {{9001_auth}}{{consent_verifier}}&{{client_id}}&{{redirect_url}}&{{scope}}&{{response_type}}&{{state}}&{{auth-tailpart}}
### http://192.168.99.100:4444/oauth2/auth?audience=&client_id=auth-code-client&consent_verifier=a643ae2e056543fabbd8d6f747e8a30c&max_age=0&nonce=chscixgzceuosfcocvvmjngj&prompt=&redirect_uri=http%3A%2F%2F127.0.0.1%3A5555%2Fcallback&response_type=code&scope=openid+offline&state=oplovvughuyzixqdvxnortrq

@token= xLPcJ3tobDqGUDxIVTxWt2p7w_odZSV22IAlUf5QPZU.YD6R_xKQ2ldCLbEV7mmc01E6ZLzemzdEC5H4-otTMPg
### userinfo
GET https://openid.hydra:9001/userinfo
Authorization: Bearer {{token}}
### introspect
POST https://openid.hydra:9002/oauth2/introspect
Content-Type: application/x-www-form-urlencoded

token={{token}}
&scope=openid+photos.read

###
GET https://openid.hydra:9002/oauth2/auth/sessions/consent?subject=foo@bar.com HTTP/1.1

PS:&scope=openid+photos.read can remove.

PS:
Here REST Client still return login page. go main server error log:

Post https://openid.hydra:9001/oauth2/token: x509: certificate signed by unknown authority


This is Go Server problem. See main.go Line:55-61 82-94 Fix this problem.




========== old ==========

3、Now have problem is token user. When you run *A, try to open web broswer. http://192.168.99.100:9010 then click "Authorize application" get error.
Because "Authorize application" still is 127.0.0.1. No way to change. So copy Link change it.


https://192.168.99.100:9001/oauth2/auth?audience=&client_id=auth-code-client&max_age=0&nonce=ylnybhabgcjllcxbfvhfjdfe&prompt=&redirect_uri=http%3A%2F%2F192.168.99.100%3A9010%2Fcallback&response_type=code&scope=openid+offline+photos.read&state=shqjytubxbrzqwtiskwwpfdp

Copy fix link to go. Fllow website.


4、The Big problem is Allow access only get error. Can't know why.


Rest Client || visual studio code

Even by step to run. Still get error......

OpenID grant_type

https://blog.yorkxin.org/2013/09/30/oauth2-3-endpoints.html

Grant Type
Grant Type 透過 grant_type 參數來指定,其值定義如下:

值 意義
authorization_code 用 Authorization Code 求 Access Token (Authorization Code Grant Flow)。
password 用 Resorce Owner Password Credentials 求 Access Token (Resource Owner Password Credentials Grant Flow)。
client_credentials 用 Client Credentials 求 Access Token (Client Credentials Grant Flow)。
refresh_token 用 Refresh Token 換發 Access Token。

OpenID hydra dex

F... Now follow step run, Get level=error msg="An error occurred" debug="No CSRF value available in the session cookie" description="The request is not allowed" error=request_forbidden hint="You are not allowed to perform this action."

If you run same broswer and restart docker or clear cookie, do many way. Just try broswer private mode.



Try dex docker or binary failed, it's be pass.

Hydra docker-compose

1、get https://github.com/ory/hydra



docker-compose -f quickstart.yml -f quickstart-postgres.yml up --build

注意 quickstart.yml



run docker on host or run binary on host. hydra 5 minutes demo "IP Used" is 127.0.0.1



version: '3'

services:

  hydra:
    image: oryd/hydra:latest
    ports:
      - "4444:4444" # Public port
      - "4445:4445" # Admin port
      - "5555:5555" # Port for hydra token user
    command:
      serve all --dangerous-force-http
    environment:
      - URLS_SELF_ISSUER=http://127.0.0.1:4444
      - URLS_CONSENT=http://127.0.0.1:3000/consent
      - URLS_LOGIN=http://127.0.0.1:3000/login
      - URLS_LOGOUT=http://127.0.0.1:3000/logout
      - DSN=memory
      - SECRETS_SYSTEM=youReallyNeedToChangeThis
      - OIDC_SUBJECT_TYPES_SUPPORTED=public,pairwise
      - OIDC_SUBJECT_TYPE_PAIRWISE_SALT=youReallyNeedToChangeThis
    restart: unless-stopped

  consent:
    environment:
      - HYDRA_ADMIN_URL=http://hydra:4445
    image: oryd/hydra-login-consent-node:latest
    ports:
      - "3000:3000"
    restart: unless-stopped


run VM or real server is real ip. Ex: 192.168.99.100 (docker-machine)




version: '3'

services:

  hydra:
    image: oryd/hydra:latest
    ports:
      - "4444:4444" # Public port
      - "4445:4445" # Admin port
      - "5555:5555" # Port for hydra token user
    command:
      serve all --dangerous-force-http
    environment:
      - URLS_SELF_ISSUER=http://192.168.99.100:4444
      - URLS_CONSENT=http://192.168.99.100:3000/consent
      - URLS_LOGIN=http://192.168.99.100:3000/login
      - URLS_LOGOUT=http://192.168.99.100:3000/logout
      - DSN=memory
      - SECRETS_SYSTEM=youReallyNeedToChangeThis
      - OIDC_SUBJECT_TYPES_SUPPORTED=public,pairwise
      - OIDC_SUBJECT_TYPE_PAIRWISE_SALT=youReallyNeedToChangeThis
    restart: unless-stopped

  consent:
    environment:
      - HYDRA_ADMIN_URL=http://hydra:4445
    image: oryd/hydra-login-consent-node:latest
    ports:
      - "3000:3000"
    restart: unless-stopped


If have cors problems. see https://github.com/ory/hydra/blob/master/quickstart-cors.yml


Check hydra OpenID startup or not 確認是否正常啟動


http://192.168.99.100:4444/.well-known/jwks.json  


Create clients


Download hydra binary.

https://www.ory.sh/docs/next/hydra/install#download-binaries
https://github.com/ory/hydra/releases
https://github.com/ory/hydra/releases/tag/v1.0.0-rc.15

PS: Maybe version renew, so try to get best new.


hydra clients create --endpoint http://192.168.99.100:4445/ --id auth-code-client --secret secret --grant-types authorization_code,refresh_token --response-types code,id_token --scope openid,offline --callbacks http://127.0.0.1:5555/callback

! new version use endpoint, different before auth-url and token-url, But I think you still can use old way... Maybe

! scope "openid,offline" next step must use same. So scope is definend by yourself.

Thanks https://dotblogs.com.tw/liguobao/2018/12/30/132746


Check clients 查看clients


hydra clients list --endpoint http://192.168.99.100:4445 


Emu all step OpenID


Fllow website that run command pop website. If no pop, http://127.0.0.1:5555/



hydra token user --client-id auth-code-client --client-secret secret --endpoint http://192.168.99.100:4444 --port 5555 --scope openid,offline

This step will run server on port 5555

! here scope "openid,offline" must same before create.








Get userinfo. Copy Access Token replace string after Bearer



curl -X GET http://192.168.99.100:4444/userinfo -H 'Accept: application/json' -H 'Authorization: Bearer MmadDHs3VdWC7LZTIdBKUHyzgsWHe2XbzHpwjKrF7Rs.tXlg7rShEEbkcczNWJGS84sIvokTF6Ae7bhSQZfHMgA' 

Get json
{"sid":"c7d5665b-76e7-475a-95a8-cc521352663b","sub":"foo@bar.com"}


Modify edit add userinfo info.


https://github.com/ory/hydra-login-consent-node/blob/master/routes/login.js
subject: 'foo@bar.com', -> subject: 'foo@bar.com-success',


This docker test
1. docker ps
2. get oryd/hydra-login-consent-node:v1.0.0-rc.10 containerid
3. docker exec -it containerid /bin/sh
4. vi bin/www change port 3000 - > 3001
5. vi routes/login.js subject: 'foo@bar.com', => subject: 'foo@bar.com--success',
5. node ./bin/www &
6. ps
7. kill old node (be exit container)
8. docker exec -it containerid /bin/sh
9. vi bin/www change port 3001 - > 3000
10. node ./bin/www &
11. kill old node (be exit container)
12. docker exec -it containerid /bin/sh
13. netstat -nlp (check port 3000)


====================
https://mileschou.github.io/auth-notes/src/hydra/user-login-and-consent-flow.html#oauth-2-0-%E8%88%87-open-id-connect
====================
https://dotblogs.com.tw/liguobao/2018/12/30/132746
OAUTH2_ISSUER_URL hydra所在的地址
OAUTH2_CONSENT_URL 授权页面地址
OAUTH2_LOGIN_URL 登录页面地址

XX应用请求授权
-> 跳转到OAUTH2_LOGIN_URL地址
-> 登录成功
->跳转到OAUTH2_CONSENT_URL授权页面
-> 授权成功
->回调XX应用地址并且返回相关授权code/token
-> XX应用使用code/token获取用户信息或者其他操作