OmniAuth OpenID Connect

repository·master·Indexed 41 days ago

https://github.com/omniauth/omniauth_openid_connect

An OmniAuth strategy that enables OpenID Connect (OIDC) authentication for Ruby applications. It supports OIDC Discovery, PKCE, and integration with Rails and Devise. Compatible with Ruby versions 2.7 through 3.4.

Tokens
4.3K
Snippets
8
Records
14
Agent score
50%

What's inside OmniAuth OpenID Connect

  1. How OpenID Connect Discovery works

    master

    OpenID Connect Discovery allows the gem to automatically fetch configuration from the provider.

    1. Set discovery: true in your provider configuration.
    2. The gem will attempt to find the configuration via the provider's Webfinger endpoint or the issuer URL.
    3. If using issuer, the gem fetches configuration from [issuer]/.well-known/openid-configuration.

    When discovery is used, manual settings for authorization_endpoint, token_endpoint, userinfo_endpoint, jwks_uri, and end_session_endpoint are replaced by the discovered values.

  2. Configure OmniAuth::OpenIDConnect with Devise

    master

    When integrating with Devise, use the config.omniauth method within the Devise.setup block.

    Important: If using Devise, it is highly recommended to keep the provider name as :openid_connect. Using a custom name might cause Devise to route to users/auth/:provider instead of the expected users/auth/openid_connect path.

    Devise.setup do |config|
      config.omniauth :openid_connect, {
        name: :my_provider,
        scope: [:openid, :email, :profile, :address],
        response_type: :code,
        uid_field: "preferred_username",
        client_options: {
          port: 443,
          scheme: "https",
          host: "myprovider.com",
          identifier: ENV["OP_CLIENT_ID"],
          secret: ENV["OP_SECRET_KEY"],
          redirect_uri: "http://myapp.com/users/auth/openid_connect/callback",
        },
      }
    end
  3. Handle stateless callback requests for mobile apps

    master

    If you are building a stateless client (such as a mobile app) where the session is empty, you can bypass the initial phase and go straight to the callback phase. To do this, you must forward specific parameters received from the client as request parameters to your /callback endpoint.

    Currently supported parameters for forwarding are:

    • code_verifier
    • nonce
  4. Install omniauth_openid_connect

    master

    To use omniauth_openid_connect in your Ruby application, add the gem to your Gemfile and run bundle.

    Alternatively, you can install the gem directly via the command line.

    # Add to Gemfile
    gem 'omniauth_openid_connect'

    Then run

    $ bundle

    Or install directly

    $ gem install omniauth_openid_connect

  5. Configure OmniAuth::OpenIDConnect in Rails

    master

    To use omniauth-openid-connect in a standard Rails application, add the provider to your middleware stack using OmniAuth::Builder. You must provide a client_options hash containing connection details like identifier, secret, and host.

    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :openid_connect, {
        name: :my_provider,
        scope: [:openid, :email, :profile, :address],
        response_type: :code,
        uid_field: "preferred_username",
        client_options: {
          port: 443,
          scheme: "https",
          host: "myprovider.com",
          identifier: ENV["OP_CLIENT_ID"],
          secret: ENV["OP_SECRET_KEY"],
          redirect_uri: "http://myapp.com/users/auth/openid_connect/callback",
        },
      }
    end
  6. Configure OmniAuth::OpenIDConnect client options

    master

    The client_options hash is used to configure the underlying OpenID Connect client. This includes connection details, endpoints, and credentials. If discovery: true is set, many of these endpoints can be automatically populated from the provider's discovery document.

    option :client_options, identifier: nil,
                            secret: nil,
                            redirect_uri: nil,
                            scheme: 'https',
                            host: nil,
                            port: 443,
                            audience: nil,
                            authorization_endpoint: '/authorize',
                            token_endpoint: '/token',
                            userinfo_endpoint: '/userinfo',
                            jwks_uri: '/jwk',
                            end_session_endpoint: nil
  7. Configure OmniAuth::OpenIDConnect strategy options

    master

    The strategy accepts several top-level options to control the OpenID Connect flow. Key options include:

    • issuer: The URL of the OpenID provider.
    • discovery: Boolean. If true, endpoints are discovered via the issuer URL.
    • scope: Array of scopes (defaults to [:openid]).
    • response_type: The response type (e.g., 'code' or 'id_token').
    • pkce: Boolean. Enables Proof Key for Code Exchange.
    • uid_field: The field in the user info used as the unique identifier (defaults to 'sub').
    • logout_path: The path used to trigger the end-session flow (defaults to '/logout').
  8. Reference: Client Configuration Options

    master

    These options are passed within the client_options hash. Many of these fields are automatically populated if discovery: true is used.

    | Field | Description | Default | Replaced by discovery? |
    |-------|-------------|---------|------------------------|
    | identifier | The OAuth2 client_id | | |
    | secret | The OAuth2 client secret | | |
    | redirect_uri | The OAuth2 authorization callback url in your app | | |
    | scheme | The http scheme to use | `https` | |
    | host | The host of the authorization server | `nil` | |
    | port | The port for the authorization server | `443` | |
    | audience | The intended consumer (`aud` field) of the id_token | `nil` | |
    | authorization_endpoint | The authorize endpoint on the authorization server | `/authorize` | yes |
    | token_endpoint | The token endpoint on the authorization server | `/token` | yes |
    | userinfo_endpoint | The user info endpoint on the authorization server | `/userinfo` | yes |
    | jwks_uri | The jwks_uri on the authorization server | `/jwk` | yes |
    | end_session_endpoint | The url to call to log the user out at the authorization server | `nil` | yes |
  9. Reference: OmniAuth Provider Options

    master

    These are the top-level configuration options for the openid_connect provider. Note that issuer and client_options are required.

    | Field | Description | Required | Default | Example/Options |
    |-------|-------------|----------|---------|-----------------|
    | name | Arbitrary string to identify connection and identify it from other openid_connect providers | no | String: `openid_connect` | `:my_idp` |
    | issuer | Root url for the authorization server | yes | | `https://myprovider.com` |
    | discovery | Should OpenID discovery be used. This is recommended if the IDP provides a discovery endpoint. | no | `false` | `true`, `false` |
    | client_auth_method | Which authentication method to use to authenticate your app with the authorization server | no | Sym: `:basic` | `"basic"`, `"jwks"` |
    | scope | Which OpenID scopes to include (:openid is always required) | no | Array<sym>: `[:openid]` | `[:openid, :profile, :email]` |
    | response_type | Which OAuth2 response type to use with the authorization request | no | String: `code` | `'code'`, `'id_token'` |
    | state | A value to be used for the OAuth2 state parameter. Can be a proc that generates a string. | no | Random 16 character string | `Proc.new { SecureRandom.hex(32) }` |
    | require_state | Should the callback phase require that a state is present. | no | `true` | `false` |
    | send_state | Should the authorize phase send a `state` parameter | no | `true` | `false` |
    | response_mode | The response mode per spec | no | `nil` | `:query`, `:fragment`, `:form_post`, `:web_message` |
    | display | Optional parameter to determine how the authorization and consent page is displayed | no | `nil` | `:page`, `:popup`, `:touch`, `:wap` |
    | prompt | Optional parameter to determine what pages the user will be shown | no | `nil` | `:none`, `:login`, `:consent`, `:select_account` |
    | send_scope_to_token_endpoint | Should the scope parameter be sent to the authorization token endpoint? | no | `true` | `true`, `false` |
    | post_logout_redirect_uri | The logout redirect uri to use per the session management draft | no | empty | `https://myapp.com/logout/callback` |
    | uid_field | The field of the user info response to be used as a unique id | no | `'sub'` | `"sub"`, `"preferred_username"` |
    | extra_authorize_params | A hash of extra fixed parameters that will be merged to the authorization request | no | Hash | `{"tenant" => "common"}` |
    | allow_authorize_params | A list of allowed dynamic parameters that will be merged to the authorization request | no | Array | `[:screen_name]` |
    | pkce | Enable PKCE flow | no | `false` | `true`, `false` |
    | pkce_verifier | Specify a custom PKCE verifier code. | no | A random 128-char string | `Proc.new { SecureRandom.hex(64) }` |
    | pkce_options | Specify a custom implementation of the PKCE code challenge/method. | no | SHA256(code_challenge) in hex | Proc to customise the code challenge generation |
    | client_options | A hash of client options detailed in its own section | yes | | |
    | jwt_secret_base64 | For HMAC with SHA 2 signing algorithms, specify the base64-encoded secret used to sign the JWT token. | no | `client_options.secret` | `"bXlzZWNyZXQ=\n"` |
    | logout_path | The log out is only triggered when the request path ends on this path | no | `'/logout'` | `'/sign_out'` |
    | acr_values | Authentication Class Reference (ACR) values to be passed to the authorize_uri | no | `nil` | `"c1 c2"` |
  10. Handle OpenID Connect authentication errors

    master

    When using omniauth-openid-connect, authentication failures may raise specific error classes within the OmniAuth::OpenIDConnect namespace. You can rescue these errors to provide custom error handling or logging during the authentication flow.

    Common error classes include:

    • OmniAuth::OpenIDConnect::Error: The base error class for all OpenID Connect related errors.
    • OmniAuth::OpenIDConnect::MissingCodeError: Raised when the authorization code is missing from the callback.
    • OmniAuth::OpenIDConnect::MissingIdTokenError: Raised when the ID Token is missing from the response.
    begin
      # Authentication logic that might trigger OmniAuth::OpenIDConnect errors
    rescue OmniAuth::OpenIDConnect::MissingCodeError => e
      # Handle missing authorization code
    rescue OmniAuth::OpenIDConnect::MissingIdTokenError => e
      # Handle missing ID token
    rescue OmniAuth::OpenIDConnect::Error => e
      # Handle generic OpenID Connect errors
    end