Hydra project introduction

Hydra is introduced

ORY Hydra is an enhanced, OpenID-certified OAuth 2.0 server and OpenID Connect provider optimized for low latency, high throughput and low resource consumption. ORY Hydra is not an identity provider (user registration, user login, password reset process), but connects to your existing identity provider through login and consent applications. It is easy to implement login and consent applications in different languages, and sample consent applications (Go, Node) and SDKS are provided.

1 Code Download

Hydra source address to download

2 Initial Database

2.1 Compile the project into main.exe

Go to the root directory of the Hydra project and run the following command to generate an executable file main.exe

go build main.go
Copy the code

2.2 Initializing the Database

Go to the root directory of the Hydra project

2.2.1 Create a database hydra with Navicat

2.2.2 Data migration for the Hydra Project

Enter the database connection information to migrate data

The main. Exe migrate SQL mysql: / / root: admin @ TCP/hydra (127.0.0.1:3306)Copy the code

2.2.3 Check whether the migration is successful in Navicat

3 config. Yaml explanation

# ORY Hydra project configuration file

#!!!!! Warning!!!!! This configuration file is used for documentation purposes only. Do not use it in production. As all configuration items.

# ORY Hydra can be configured using configuration files and using '--config path/to/config.yaml' to pass file locations.
# By default, ORY Hydra will find and load the file ~/.hydra.yaml. All configuration keys can also be set using environment variables.

## Set the environment variable introduction to start ##
Setting environment variables is easy:
## Linux / OSX
#
# $ export MY_ENV_VAR=foo
# $ hydra ...
#
# 或者:
# $ MY_ENV_VAR=foo hydra ...
#
## Windows
#
Open a command prompt
#
# > set MY_ENV_VAR=foo
# > hydra ...
#
### Powershell
#
# > $env:MY_ENV_VAR="foo"
# > hydra ...
#
## Docker
#
# $ docker run -e MY_ENV_VAR=foo oryd/hydra:...
#
## End of setting environment variables introduction ##

# assume the configuration layout is as follows:
#
# serve:
# public:
# port: 4444
# something_else: foobar
#
The # key "something_else" can be set as an environment variable by marking its path:
# `serve.public.port.somethihng_else` -> `SERVE.PUBLIC.PORT.SOMETHING_ELSE`
# and replace '. 'with' _ ':
# `serve.public.port.somethihng_else` -> `SERVE_PUBLIC_PORT_SOMETHING_ELSE`
#
Environment variables always override values in configuration files. Here are some more examples:
#
# Configuration key | Environment variable |
# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - |
# dsn | DSN |
# serve.admin.host | SERVE_ADMIN_HOST |
# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - |
#
#
List items, for example
#
# secrets:
# system:
# - this-is-the-primary-secret
# - this-is-an-old-secret
# - this-is-another-old-secret
#
When using environment variables, you must separate them with a ','. The environment variable equivalent to the code part # above is:
#
# Linux/macOS: $ export SECRETS_SYSTEM=this-is-the-primary-secret,this-is-an-old-secret,this-is-another-old-secret
# Windows: > set SECRETS_SYSTEM=this-is-the-primary-secret,this-is-an-old-secret,this-is-another-old-secret

Configure the logger
log:
 Set the log level. The parameters can be "panic", "fatal", "error", "WARN ", "info" and "debug". The default level is info
  level: info
  Set the log format. No text-based log format is defined or set to JSON format.
  format: json

Service control configuration of the HTTP (S) daemon
serve:
  Public control public daemons that serve public API endpoints, such as /oauth2/auth, /oauth2/token, /.well-known/jwks.json
  public:
    Public API endpoint service to listen on the port number, default is 4444
    port: 4444
    Hydra should listen for and process public API requests.
    Use the prefix "Unix:" to specify the path of the Unix socket. Leave empty listeners on all interfaces.
    host: localhost On all default devices, remove or leave this empty to listen
    # host: unix:/path/to/socket

    # Cors configures cross-domain resource sharing for common endpoints.
    cors:
      # Set enable to true to enable CORS. The default is false.
      enabled: true
     # allowed_origins is a list of origins (comma-separated values) that can perform a cross-domain request.
     All origins will be allowed if there is a special * value in the listing. The origin can contain a wildcard character (*) to replace zero or more characters (i.e. http:// *. Domain.com).
     You can only use one wildcard per origin. If empty or undefined, the default is' * ', allowing CORS from each domain (CORS: true if enabled).
      allowed_origins:
        - https://example.com
        - https://*.example.com
      # Allow methods are HTTP method list requests that allow user agents to use with cross-domain. The default is the listed method.
      allowed_methods:
        - POST
        - GET
        - PUT
        - PATCH
        - DELETE

      A list of non-simple headers that clients are allowed to use in cross-domain requests. Defaults to the listed values.
      allowed_headers:
        - Authorization
        - Content-Type

      Set which titles (comma-separated values) are safely exposed to the CORSAPI specification's API. Defaults to the listed values.
      exposed_headers:
        - Content-Type

      Set whether the request can include user credentials such as cookies, HTTP authentication, or client SSL certificates. The default is true
      allow_credentials: true
      Set the time (in seconds) for which the results of pre-flight requests can be cached.
      If set to 0, each request is preceded by a preflight request. The default is 0.
      max_age: 10

      # If set to true, additional log output is added to debug server-side CORS issues. The default is false.
      debug: true

    Configure access logging for public servers.
    access_log:
      Disable access logging for healthy endpoints.
      disable_for_health: false

      # admin controls admin daemons that serve adminAPI endpoints, such as/JWK, /client...
  admin:
    The default port number monitored by the admin API endpoint service is 4445
    port: 4445
    # The interface or Unix socket Ory Hydra should listen for and process administrative API requests.
    # Use the prefix "Unix" to specify the path of the Unix socket. Leave empty listeners on all interfaces.
    host: localhost # omit or empty listen to all devices, this is the default.
    # host: unix:/path/to/socket

    # cORS configures the Admin endpoint for Cross Origin resource sharing.
    cors:
      # Set enable to true to enable CORS. The default is false.
      enabled: true
      # allowed_origins is a list of sources (comma-separated values) from which cross-domain requests can be performed.
      All origins are allowed if there is a special * value in the list. Origin can contain wildcards (*)
      # Replace zero or more characters (that is: http://*.domain.com). Only one wildcard can be used per origin.
      # If empty or undefined, the default is "*", allowing CORS from each domain (if cers.enabled :true).
      allowed_origins:
        - https://example.com
        - https://*.example.com
      # allowed_methods is a list request for HTTP methods that allow user agents to use across domains. The default is GET and POST.
      allowed_methods:
        - POST
        - GET
        - PUT
        - PATCH
        - DELETE

      A list of non-simple headers that clients are allowed to use for cross-domain requests. Defaults to the listed values.
      allowed_headers:
        - Authorization
        - Content-Type

      # Set which headers (comma-separated values) can be safely exposed to the CORS API specification API. Defaults to the listed values.
      exposed_headers:
        - Content-Type

    # set whether the request can include user credentials such as cookies, HTTP authentication, or client SSL certificates.
      allow_credentials: true
      Set the time (s) in which results of pre-flight requests can be cached. If set to 0, each request is requested before flight. The default is 0.
      max_age: 10

      # If set to true, additional log output will be added to debug server-side CORS problems. The default is false.
      debug: true

    Manage server access log configuration.
    access_log:
      Disable access logging for healthy endpoints.
      disable_for_health: false

  # TLS Configure HTTPS (HTTP over TLS). If configured, the server automatically supports HTTP/2.
  tls:
    Key configuration private key (PEM encoding)
    key:
      # key can be loaded from a file, to generate the secret key at https://www.selfsignedcertificate.com/
      path: ./docs/hydra_private.key
      # or from a Base64 encoded (without padding) string:
      #base64: LS0tLS1CRUdJTiBFTkNSWVBURUQgUFJJVkFURSBLRVktLS0tLVxuTUlJRkRqQkFCZ2txaGtpRzl3MEJCUTB3...

    # cert configures the TLS certificate (PEM encoded)
    cert:
      # certificate can be loaded from a file: the secret key generated web site, https://www.selfsignedcertificate.com/
      path: ./docs/hydra_certificate.cert
      # or from a Base64 encoded (without padding) string:
      #base64: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tXG5NSUlEWlRDQ0FrMmdBd0lCQWdJRVY1eE90REFOQmdr...

    Whitelist one or more CIDR address ranges and allow them to terminate TLS connections.
    Please note that the X-Forwarded-Proto header must be set, except for your proxy/gateway/load balancer. Ipv4 and ipv6 are supported.
    #
    # Hydra provides HTTP instead of HTTPS when this option is set.
    # for more information, please visit: https://www.ory.sh/docs/hydra/production#tls-termination
    allow_termination_from:
      - 127.0. 01./ 32

# DSN sets the data source name. This will configure the ORY Hydra back end where the data is stored.
#
# memory database
#
If DSN is "memory", data will be written to memory and lost when this instance is restarted. This value can be set using the DSN environment variable:
#
# SQL database
#
# ORY Hydra supports popular SQL databases. For more detailed configuration information, please go to: https://www.ory.sh/docs/hydra/dependencies-environment#sql

#PostgreSQL (recommended)
# If DSN uses postgres:// PostgreSQL as back-end storage database: Connect DSN as shown in the following example
# dsn: dsn=postgres://user:password@host:123/database
#
### MySQL database
# if DSN uses mysql:// mysql as the back-end storage database: Connect DSN as shown in the following example
# dsn: mysql://user:password@tcp(host:123)/database


### CockroachDB
# If DSN takes COCKROACH :// CockroachDB as its back-end storage database: Connect DSN as shown in the following example
# dsn: cockroach://user:password@host:123/database
#
dsn: Mysql: / / root: admin @ TCP/hydra (127.0.0.1:3306)

# webfinger configuration./well-known/ Settings
webfinger:
  # JWKS configuration /.well-known/jwks.json endpoint.
  jwks:
    The broadcast key is a list of JSON Web keys that should be exposed at that endpoint. This is usually
    The public key used to validate the OpenID Connect ID token. However, you may need to add additional keys here as well.
    broadcast_keys:
      - hydra.openid.id-token By default, this key is always public
      # -hydra.jwt. Access -token # This key will be exposed when OAuth2 access token policy is set to JWT.

  #oidc_discovery OpenID Connect Discovery (/.well-known/OpenID)
  oidc_discovery:
    client_registration_url: https://my-service.com/clients
    A list of supported declarations to broadcast. Always include the statement "sub" :
    supported_claims:
      - email
      - username
    # scope OAuth 2.0 clients can request. Always include scopes "offline", "offline\u Access", and "openID".
    supported_scope:
      - email
      - whatever
      - read.photos

    # The URL discovery endpoint of the Userinfo endpoint to be published on OpenID Connect /.well-known/ OpenID configuration.
    # default is ORY Hydra userinfo endpoint, located at /userinfo. Set this value if you want to handle this endpoint yourself.
    userinfo_url: https://example.org/my-custom-userinfo-endpoint

# oIDC configures OpenID Connect.
oidc:
  # subject_identifiers configures the Subject Identifier algorithm
  # for more information, please refer to the document: https://www.ory.sh/docs/hydra/advanced#subject-identifier-algorithms
  subject_identifiers:
    # Which algorithms to enable. The default is "public"
    enabled:
      - pairwise
      - public
    Configure the pair algorithm
    pairwise:
      If pairs are enabled, the salt attribute must be defined
      salt: some-random-salt

  OpenID Connect Dynamic client registry (exposed as management endpoint /clients/...)
  dynamic_client_registration:

    # OpenID Connect Dynamic client registration specification has no concept of whitelist OAuth 2.0 scope.
    If you want to expose dynamic client registries, set the default scope enabled for newly registered clients.
    # Remember that users can override this default value by setting the "scope" key in the registration payload, effectively disabling the concept of whitelist scope.
    default_scope:
      - openid
      - offline
      - offline_access

urls:
  self:
    # This value will be used as the "issuer" in the access and ID tokens. HTTPS must be specified and used unless --dangerous-force-http is set.
    # This should usually be equal for public value.
    issuer: https://localhost:4444/

    This is the base location of the common endpoint for ORY Hydra installations. This should normally be equal in value to the issuer.
    If not specified, the issuer value is returned.
    public: https://localhost:4444/

  # set the login attribute to the endpoint of the user login and consent stream. The default is internal rollback URL.
  login: https://my-login.app/login
  Set consent node attribute, the endpoint of the user login and consent stream. The default is internal rollback URL.
  consent: https://my-consent.app/consent
  Set the logout endpoint. The default is internal rollback URL.
  logout: https://my-logout.app/logout
  Set the wrong endpoint. When an OAuth2 error occurs and cannot be sent back, the error page is displayed to the customer. The default is internal rollback URL.
  error: https://my-error.app/error
  When the user agent requests logout, it will be redirected to this URL by default.
  post_logout_redirect: https://my-example.app/logout-successful

strategies:
  scope: DEPRECATED_HIERARCHICAL_SCOPE_STRATEGY
  You can use JSON Web tokens as access tokens.
  # But seriously. Don't do that. This is not a good idea, with lots of caveats and subtle security implications. Read more: https://www.ory.sh/docs/hydra/advanced#json-web-tokens
  #
  # access_token: jwt

Configure the lifetime
ttl:
  Configure how long it may take for the user to log in and agree to the flow. The default value is 1 hour.
  login_consent_request: 1h
  Configure the time when the access token is valid. The default value is 1 hour.
  access_token: 1h
  Configure the duration of the refresh token. The default value is 720h. Set to -1 to make the refresh token never expire.
  refresh_token: 720h
  # configure the duration of the token. The default value is 1 hour.
  id_token: 1h
  Configure the time when the validation code is valid. The default value is 10 seconds.
  auth_code: 10m

oauth2:
  Set this to true if you want to share error debugging information with OAuth 2.0 clients.
  # Remember that debugging information is very valuable when dealing with errors, but it can also expose database errors, code, and similar errors. The default is false.
  expose_internal_errors: true
  Configure the hash algorithm. Currently, only BCrypt is supported
  hashers:
    Configure the BCrypt hash algorithm for hashing client secrets.
    bcrypt:
      # Set BCrypt cost. The minimum value is 4 and the default value is 10. The higher the value, the more CPU time is used to generate the hash.
      cost: 10
  pkce:
    Set this to true if you want to enforce PKCE on all clients.
    enforced: false

The # secrets section configures secrets for encrypting and signing multiple systems. All secrets can spin,
# For more information on this topic, navigate to:  https://www.ory.sh/docs/hydra/advanced#rotation-of-hmac-token-signing-and-database-and-cookie-encryption-keys
secrets:
  The system secret must be at least 16 characters long. If none is provided, one will be generated.
  # They are keys for encrypting sensitive data using AES-GCM (256 bits) and verifying HMAC signatures.
  # The first item in the list is used for signing and encryption. The entire list is used for signature verification and decryption.
  system:
    - this-is-the-primary-secret
    - this-is-an-old-secret
    - this-is-another-old-secret
  # Used to encrypt the secret of the cookie session. The default is secrets.system. A separate production secret is recommended.
  # The first item in the list is used for signing and encryption. The entire list is used for signature verification and decryption.
  cookie:
    - this-is-the-primary-secret
    - this-is-an-old-secret
    - this-is-another-old-secret

If set, enable analysis. Use CPU to enable CPU analysis and mem to enable memory analysis. More details on the analysis, go to: https://blog.golang.org/profiling-go-programs
profiling: cpu
# profiling: mem

#ORY Hydra supports distributed tracking.
tracing:
  Set this as the trace back end to use. Jaeger is currently supported. If omitted or null, tracing is disabled.
  provider: jaeger
  # specify the name of the service to use on the tracer.
  service_name: ORY Hydra
  providers:
    Configure jaeger to track the back end.
    jaeger:
      # Jaeger agent should send SPANS to the address
      local_agent_address: 127.0. 01.: 6831
      # trace header format
      propagation: jaeger
      sampling:
        The type of sampler to use. Support:
        # - const
        # - probabilistic
        # - ratelimiting
        type: const
        The value passed to the configured sampler type. Supported values: This depends on the sampling strategy used:
        # - const: 0 or 1 (all or none)
        # rateLimiting (rate limit) : Constant rate (e.g., setting this to 3 will sample requests at a rate of 3 traces per second)
        # - rateLimiting: 3
        # A value between 0 and 1, such as 0.5
        # - probabilistic: 0.5
        value: 1.0
        # jaeger proxy HTTP sampling server address
        server_url: http://localhost:5778/sampling
Copy the code

4 Starting the Project

Go to the root directory of the Hydra project and run the following command. For more commands, see main.exe -h

main.exe serve all --config ./docs/config.yaml
Copy the code

5 View the project interface document

Go to the root directory of the Hydra project and run the following command. For more commands, see swagger -h

swagger serve -F=swagger ./docs/api.swagger.json
Copy the code

6 Front-end Projects

Hydra – the login – consent – node to download

6.1 Configuration File Description

Binding the backend server address, configuration file location in the hydra – login – consent – node – master/services/hydra js, the following figure

6.2 Front-end Directory Structure

7 Description of ports

7.1 Flowchart Description

The following is part of the interface documentation. For more request parameters, please refer to swagger documentation

7.2 Creating an Oauth2 Client

7.2.1 Interface Description

  • Request mode :POST
  • The requested URL: http://127.0.0.1:4445/clients
  • Note:127.0.0.1:4445For the backgroundAdmin APIThe endpoint service

7.2.2 Request Parameters

Request parameters The parameter types Parameters that
client_id string The client id
client_name string Client name
client_secret string Client secret key
client_secret_expires_at string Expiration time of the client key
created_at string Client creation time
frontchannel_logout_session_required string Log out of the session. 0 No. 1 Yes
scope string Scope of the client
token_endpoint_auth_method string Token endpoint authentication method
grant_types string Grant type
response_types An array of Response type

7.2.3 Example of Request Parameters

{
    "client_id":"what-client"."client_name":"whatOAuth2.0"."client_secret":"what-secret"."client_secret_expires_at":0."client_uri":"http://127.0.0.1:5555/callback"."created_at":"The 2020-01-06 T15:09:15. 946 z"."frontchannel_logout_session_required":false."scope":"openid offline offline_access"."token_endpoint_auth_method":"client_secret_basic"."updated_at":"The 2020-01-07 T15:09:15. 946 z"."userinfo_signed_response_alg":"none"."grant_types": [
    "client_credentials"]."response_types": [
    "code"]}Copy the code

7.2.4 Example of Creating a Response on a Client

{
    "client_id": "what-client"."client_name": "whatOAuth2.0"."client_secret": "what-secret"."redirect_uris": null."grant_types": [
        "client_credentials"]."response_types": [
        "code"]."scope": "openid offline offline_access"."audience": null."owner": ""."policy_uri": ""."allowed_cors_origins": null."tos_uri": ""."client_uri": "http://127.0.0.1:5555/callback"."logo_uri": ""."contacts": null."client_secret_expires_at": 0."subject_type": "public"."token_endpoint_auth_method": "client_secret_basic"."userinfo_signed_response_alg": "none"."created_at": "2020-01-07T07:30:11Z"."updated_at": "2020-01-07T07:30:11Z"
}
Copy the code

7.3 Obtaining the Oauth2 Client List

7.3.1 Interface Description

  • Request mode :GET
  • The requested URL: http://127.0.0.1:4445/clients
  • Note:127.0.0.1:4445For the backgroundAdmin APIThe endpoint service

7.3.2 Response Examples

[{"client_id": "auth-code-client"."client_name": ""."redirect_uris": [
            "http://127.0.0.1:5555/callback"]."grant_types": [
            "authorization_code"."refresh_token"]."response_types": [
            "code"."id_token"]."scope": "openid offline"."audience": []."owner": ""."policy_uri": ""."allowed_cors_origins": []."tos_uri": ""."client_uri": ""."logo_uri": ""."contacts": []."client_secret_expires_at": 0."subject_type": "public"."token_endpoint_auth_method": "client_secret_basic"."userinfo_signed_response_alg": "none"."created_at": "2020-01-06T03:01:30Z"."updated_at": "2020-01-06T03:01:30Z"."metadata": null
    },
    {
        "client_id": "bbb-client"."client_name": ""."redirect_uris": [
            "http://127.0.0.1:3000/login"]."grant_types": [
            "authorization_code"."refresh_token"]."response_types": [
            "code"."id_token"]."scope": "openid offline"."audience": []."owner": ""."policy_uri": ""."allowed_cors_origins": []."tos_uri": ""."client_uri": ""."logo_uri": ""."contacts": []."client_secret_expires_at": 0."subject_type": "public"."token_endpoint_auth_method": "client_secret_basic"."userinfo_signed_response_alg": "none"."created_at": "2020-01-06T08:22:33Z"."updated_at": "2020-01-06T08:22:33Z"."metadata": null
    },
    {
        "client_id": "ccc-client"."client_name": ""."redirect_uris": []."grant_types": [
            "client_credentials"]."response_types": [
            "code"]."scope": "openid offline offline_access"."audience": []."owner": ""."policy_uri": ""."allowed_cors_origins": []."tos_uri": ""."client_uri": ""."logo_uri": ""."contacts": []."client_secret_expires_at": 0."subject_type": "public"."token_endpoint_auth_method": "client_secret_basic"."userinfo_signed_response_alg": "none"."created_at": "2020-01-06T09:29:16Z"."updated_at": "2020-01-06T09:29:16Z"."metadata": null}]Copy the code

7.4 Obtaining an Oauth2 Client

7.4.1 Interface Description

  • Request mode :GET
  • The requested URL: http://127.0.0.1:4445/clients/ {id}
  • Note:127.0.0.1:4445For the backgroundAdmin APIThe endpoint service

7.4.2 Request Parameters

Request parameters The parameter types Parameters that
id string This parameter is mandatory. Client ID
#### 7.4.3 Request Example
http://127.0.0.1:4445/clients/xxx-client
#### 7.4.4 Response Example
“`json
{
"Client_id ": "xxxOAuth2.0"," redirecT_uris ": [], "grant_types": [], "response_types": [], "scope": "openid offline offline_access", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri" : ""," client_uri ":" http://127.0.0.1:5555/callback ", "logo_uri" : ""," contacts ": [], "client_secret_expires_at": 0, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "created_at": "2020-01-07T06:25:53Z", "updated_at": "2020-01-07T06:25:53Z", "frontchannel_logout_session_required": true, "metadata": nullCopy the code

}

### 7.5 Client credentials granted #### 7.5.1 Interface Description - Request mode :POST - The request URL: [http://127.0.0.1:4444/oauth2/token] (http://127.0.0.1:4444/oauth2/token) - note: [127.0.0.1:4444](127.0.0.1:4444) for background 'public API endpoint service' #### 7.5.2 Request Parameters > Client by using add Header parameters Content-type =" Application/X-www-form-urlencoded "Request entity body sends the following parameters to make a request to the token endpoint. Note: The following parameters request to use the form - data | | parameters type | show | | -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | | grant_type | | string awarded type, Mandatory | | refresh_token | | refresh token string | | client_id | | string client id, mandatory | | client - secret | | string client secret key, Mandatory | | redirect_uri | | | string redirect uri # # # # 7.5.3 credentials awarded the background BUG * * client credentials awarded occurs the following BUG * * ` ` ` json {" error ":" invalid_client ", "error_description":"Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)", "status_code":401 }Copy the code

The reason is the Hydra source authorization code problem. Solutions are as follows:

Modify GOPATHGOPATHGOPATH/pkg/mod/github.com/ory/[email protected]/client_authentication.go file about 190 lines of code,

else if ok && form.Get(“client_id”) ! = “” && form.Get(“client_secret”) ! = “” error in judgment, modify the following code

ifoidcClient, ok := client.(OpenIDConnectClient); ! ok {// If this isn't an OpenID Connect client then we actually don't care about any of this, just continue!
} else if ok && form.Get("client_id") = ="" && form.Get("client_secret") = =""&& oidcClient.GetTokenEndpointAuthMethod() ! ="client_secret_post" {
    return nil, errors.WithStack(ErrInvalidClient.WithHintf("The OAuth 2.0 Client supports Client authentication method \"%s\ But method \"client_secret POST \" was requested. You must configure the OAuth 2.0 client's \"token_endpoint_auth_method\" value to accept \"client_secret_post\".", oidcClient.GetTokenEndpointAuthMethod()))
} else if_, _, basicOk := r.BasicAuth(); basicOk && ok && oidcClient.GetTokenEndpointAuthMethod() ! ="client_secret_basic" {
    return nil, errors.WithStack(ErrInvalidClient.WithHintf("The OAuth 2.0 Client supports Client authentication method \"%s\ But method \"client_secret_basic\" was requested. You must configure the OAuth 2.0 client's \"token_endpoint_auth_method\" value to accept \"client_secret_basic\".", oidcClient.GetTokenEndpointAuthMethod()))
} else ifok && oidcClient.GetTokenEndpointAuthMethod() ! ="none" && client.IsPublic() {
    return nil, errors.WithStack(ErrInvalidClient.WithHintf("The OAuth 2.0 Client supports Client authentication method \"%s\ But method\" none\" was requested. You must configure the OAuth 2.0 client's \"token_endpoint_auth_method\" value to accept \"none\".", oidcClient.GetTokenEndpointAuthMethod()))
}
Copy the code

7.5.4 Successful Credential Grant Example

{
    "access_token": "n5236wH87fpCoZ4AQc8QPhpysu9pDbtBH6ilZr0DwdU.lCYGIa1g48xuXzb7xj2leVSn7ACOgwWhpVxDBG9g9OI"."expires_in": 3599."scope": ""."token_type": "bearer"
}
Copy the code

7.6 Introspection on access_token

7.6.1 Interface Description

  • Request mode :POST
  • The requested URL: http://127.0.0.1:4445/oauth2/introspect
  • Note:127.0.0.1:4445For the backgroundAdmin APIThe endpoint service

7.6.2 Request Parameters

Note: Form-data is requested for the following parameters

Request parameters The parameter types Parameters that
token string Access_token is mandatory
scope string Scope of the client

7.6.3 Response Examples

{
    "active": true."client_id": "what-client"."sub": "what-client"."exp": 1578412753."iat": 1578409154."iss": "https://localhost:4444/"."token_type": "access_token"
}
Copy the code

7.7 OAuth2.0 authorization code granted

We will perform the OAuth 2.0 authorization code grant. To do this, we must first create a client capable of performing this authorization

7.7.1 Interface Description

  • Request mode :POST
  • The requested URL: http://127.0.0.1:4445/clients
  • Note:127.0.0.1:4445For the backgroundAdmin APIThe endpoint service

7.7.2 Request Parameters

Content-type =”application/x-www-form-urlencoded”

. OAuth2.0 authorization code granted. Note: the following parameter request uses form-data, where client_id is an OAuth2.0 client ID created from the client key client-secret above

Request parameters The parameter types Parameters that
client_id string The client id
client_name string Client name
client_secret string Client secret key
client_secret_expires_at string Expiration time of the client key
created_at string Client creation time
frontchannel_logout_session_required string Log out of the session. 0 No. 1 Yes
scope string Scope of the client
token_endpoint_auth_method string Token endpoint authentication method
grant_types string Grant type
response_types An array of Response type

7.7.3 Example of Request Parameters

{
    "client_id":"auth-what-client"."client_name":"Auth - whatOAuth2.0"."client_secret":"what-secret"."client_secret_expires_at":0."redirect_uris": [
    "http://127.0.0.1:5555/callback"]."created_at":"The 2020-01-06 T15:09:15. 946 z"."frontchannel_logout_session_required":false."scope":"openid offline offline_access"."token_endpoint_auth_method":"client_secret_basic"."updated_at":"The 2020-01-07 T15:09:15. 946 z"."userinfo_signed_response_alg":"none"."grant_types": [
    "authorization_code"."refresh_token"]."response_types": [
    "code"."id_token"]}Copy the code

7.8 Executing OAuth2.0 authorization code flow

The following command will start the server for the front-end Web application. The application will use ORY Hydra to execute the OAuth 2.0 authorization code flow.

7.8.1 Description of Ports

  • Request mode :POST
  • The requested URL: http://127.0.0.1:4444/oauth2/auth
  • Note:127.0.0.1:4444For the backgroundPublic API endpoint services

7.8.2 Request Parameters

Content-type =”application/x-www-form-urlencoded”

. OAuth2.0 authorization code granted. Note: the following parameter request uses form-data, where client_id is an OAuth2.0 client ID created from the client key client-secret above

Request parameters The parameter types Parameters that
client_id string OAuth2.0 Port ID, which is different from the client ID. This parameter is mandatory
client_secret string Client key. This parameter is mandatory
scope string Client scope Mandatory openID,offline
## 8 Database design document
### 8.1 Client data table hydra_client
The field names The field type Parameters that
: — — — — — – : — — — — — — — — — — — — — — — : — — — — — — — — — — — — — — — — —
id varchar(255) The client id
client_name text Client name
client_secret text Client secret key
redirect_uris text Redirect uri
grant_types text Grant type
response_types text Response type
scope text Scope of the client
owner text Client owner
policy_uri text Strategy uri
tos_uri text tos_uri
client_uri text The client uri
logo_uri text logo_uri
contacts text Client Contact
client_secret_expires_at int(11) Expiration time of the client key
sector_identifier_uri text Sector identifier
jwks text Json Web key set
jwks_uri text Json Web key set URI
request_uris text Request URIS,
token_endpoint_auth_method varchar(25) Token endpoint authentication method
request_object_signing_alg varchar(10) Request object signature
userinfo_signed_response_alg varchar(10) User information signature response
subject_type varchar(15) The topic type
allowed_cors_origins text Allow cross-domain origins
pk int(10) The primary key id
audience text visitors
created_at timestamp Creation time
updated_at timestamp Update time
frontchannel_logout_uri text Pre-channel unregister URI
frontchannel_logout_session_required tinyint(1) The front channel is required to log out of the session
post_logout_redirect_uris text Redirect the URI after exit
backchannel_logout_uri text Exit channel URI
backchannel_logout_session_required tinyint(1) Need to Exit session
metadata text metadata

8.2 Client Migration Table HYDRA_client_migration

The field names The field type Parameters that
id varchar(255) The primary key id
applied_at datetime Migrating Application Time

8.3 jsonWeb Key Data table HYDRA_JWK

The field names The field type Parameters that
sid varchar(255) Token Id of the token type
kid varchar(255) The secret key id
version int(11) The version number
keydata text The secret key data
created_at timestamp Creation time
pk int(10) A primary key

8.4 jsonWeb Key Migration Table HYDRA_Jwk_Migration

The field names The field type Parameters that
id varchar(255) The primary key id
applied_at datetime Migrating Application Time
### 8.5 Client authorization code table HYDRA_OAUTH2_ACCESS
The field names The field type Parameters that
: — — — — — – : — — — — — — — — — — — — — — — : — — — — — — — — — — — — — — — — —
signature varchar(255) The signature
request_id varchar(40) Request id
requested_at timestamp Request time
client_id varchar(255) Client ID (TABLE HYDRA_client ID)
scope text scope
granted_scope text Awarded the scope
form_data text The form data
session_data text The session data
subject varchar(255) The theme
active tinyint(1) The validity of
requested_audience text Requested visitor
granted_audience text Awarded to the visitors
challenge_id varchar(40) The challenge ID table, HYDRA_OAUTH2_CONsent_REQUEST_HANDLED, has the challenge field handled

8.6 Agreeing authentication Migration Table HYDRA_OAUTH2_AUTHENTICation_consent_migration

The field names The field type Parameters that
id varchar(255) The primary key id
applied_at datetime Migrating Application Time
### 8.7 Authentication Request table HYDRA_OAUTH2_AUTHENTICation_REQUEST
The field names The field type Parameters that
challenge varchar(40) The primary key id
requested_scope text Request scope
verifier varchar(40) Verify the id
csrf varchar(40) Cross – SiteRequestForger
subject varchar(255) The theme
request_url text The request url
skip tinyint(1) Whether to skip
client_id varchar(255) Client ID. Table HYDRA_client ID
requested_at timestamp Request time
authenticated_at timestamp Verify the time
oidc_context text OIDC context
login_session_id varchar(40) Id of login session. Table hydra_OAUTH2_AUTHENTICation_session ID
requested_at_audience text Requested visitor

8.8 THE AUTHENTICATION request has been processed HYDRA_oAUTH2_AUTHENTICation_request_HANDLED

The field names The field type Parameters that
challenge varchar(40) The primary key id
subject varchar(255) The theme
remember tinyint(1) Whether to remember
remember_for int(11) Remember the time
error text Wrong data
acr text acr
requested_at timestamp Request time completed
authenticated_at timestamp Verified time
was_used tinyint(1) Whether to use
forced_subject_identifier varchar(255) Mandatory subject identifier
context text Requested content

8.9 Authentication Session HYDRA_oAUTH2_authentication_session

The field names The field type Parameters that
id varchar(40) The primary key id
authenticated_at timestamp The session time has been verified
subject varchar(255) The theme
remember tinyint(1) Whether the memory

9 Oauth2 Third-party login example

::: tip Qq account login CSDN server Oauth2 authorization description

  1. CSDNThe site allows users to jump toQQ
  2. QQRequire the user to log in (if notQQAccount number, you need to register), then ask”CSDNWebsites ask to get their ownQQUser rights, do you agree?”
  3. The user agrees,QQIt will redirect backCSDNWebsite, and send back an authorization code.
  4. CSDNWebsites use authorization codes toQQRequest a token.
  5. QQReturn the token.
  6. CSDNWebsites use tokens to addressQQRequest user data.
  7. CSDNwithQQThe user inCSDNWrite blogs, comments, etc on the server

: : :

[img/goImage/oauth2_client.png] [img/goImage/oauth2_client.png]

10 Test the Oauth2 authorization service

10.1 Client Credential Authorization Mode

The Client Credentials Grant type is the simplest. Clients directly define their own client_id instead of the Resource owner name to request access to some protected resources on the Resource server.

[img-w9GFXO3Y-1591889699755] [img/goImage/ client-credentials.png]

10.2 Creating an OAuth 2.0 Client

See 7-2- Creating an OAuth2 client

10.3 Executing client Credentials

See 7-5- Client credential granting

10.4 Execute token introspection

See 7-6- Introspection on Access-Token

10.5 The login page is displayed

Browser, enter the following address to the backend service request, the background service returns the front login page at http://localhost:3000/login? login_challenge=ec2bf8e55a11474392f8867e92624e04

http://127.0.0.1:4444/oauth2/auth?client_id=what-client&scope=offline_access&response_type=code&state=abcdefghigklmn
Copy the code

Request Parameters

  • Request mode :GET
  • Request interface: http://127.0.0.1:4444/oauth2/auth
  • parameterclient_idIs the ID of the client created in 10.2
  • parameterresponse_typeResponse_type =code is generally fixed for the response type
  • parameterscopeScope for Client [openID offline,offline_access]
  • parameterstateA string supplied to the Client, which the server returns to the Client as is. The length must be greater than 8 bits
  • Note:127.0.0.1:4444For the backgroundPublic APIThe endpoint service

[Img-rse3wqYI-1591889699758] [IMG /goImage/ HYDRA_login.png]

10.6 Login Page

Enter the account password as prompted in the input box and click Login. The login interface is as follows

# http://127.0.0.1:4444/oauth2/auth/requests/login/accept? login interface Login_challenge = 536 e6810083947aab2bb7dda5ee6815a # http://127.0.0.1:4444/oauth2/auth? validation interface client_id=what-client&login_verifier=c7faac0f7b62457d955a00c5d95f65e2&response_type=code&6scope=offline_access&6state=ab http://127.0.0.1:4444/oauth2/auth/requests/consent? cdefghiddgklmn # proves successful return interface consent_challenge=70f9f2402e8b4ea4b07376a9dee22c52Copy the code

[img/goImage/login_success.png] [img/goImage/login_success]

Detailed description of project process

Official process description for logging in, agreeing, and logging out

11 References

  • oauth.net/2/
  • www.oauth.com/
  • RFC6749:OAuth 2.0 authorization framework
  • RFC6749 Chinese version
  • Hydra official documentation
  • How did the IBM community learn to boot Hydra
  • Github project feedback list

In_challenge = 536 e6810083947aab2bb7dda5ee6815a # http://127.0.0.1:4444/oauth2/auth? validation interface client_id=what-client&login_verifier=c7faac0f7b62457d955a00c5d95f65e2&response_type=code&6scope=offline_access&6state=ab http://127.0.0.1:4444/oauth2/auth/requests/consent? cdefghiddgklmn # proves successful return interface consent_challenge=70f9f2402e8b4ea4b07376a9dee22c52

< img/goImage/login_success.png" href="/img/goImage/login_success.png" Project detailed description process [login, agree and cancel the official process] # # 11 references - (https://www.ory.sh/docs/hydra/login-consent-flow) [https://oauth.net/2/](https://oauth.net/2/) - [https://www.oauth.com/](https://www.oauth.com/) - [RFC6749:OAuth 2.0 authorization framework] (https://tools.ietf.org/html/rfc6749) - [RFC6749 Chinese] (https://github.com/jeansfish/RFC6749.zh-cn) - [Hydra official documentation] (https://www.ory.sh/docs/hydra/) - [IBM community to learn how to guide Hydra](https://www.ibm.com/developerworks/cn/security/se-bootstrap-hydra-oauth2/index.html) - List] [making program feedback (https://github.com/ory/hydra/issues) - Reference document] [Oauth2 authentication and authorization (https://www.cnblogs.com/linianhui/category/929878.html)Copy the code