omniauth_oidc 0.2.7 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9e78d766cf25ec6bae84d2af8d007cfafd53cdc1c5f67c448b91f04d80cf8bc9
4
- data.tar.gz: 572884ae38c7d8a4c89882b8609348a6bcc5aea0c4f7e7f0303e1a4e9a763136
3
+ metadata.gz: 559ac46903a09985d800496480384fbc44b41a6c202523f239d75d6418e5d974
4
+ data.tar.gz: 6b488ff0fe44435cf6aa5f50a8ab55a39ec3a524fe55fd25eb6517c9c01408f3
5
5
  SHA512:
6
- metadata.gz: d48453b68849c0ec1a34a0d58805efb3a1cecbb4966d40e0ba4098d679330cf5d7f27b401e9a6a2d6d4f4bae4dc36224bb5b0788299358e6a8054b1c35666996
7
- data.tar.gz: b7dfad42cf0c15f34d36ce0676e79da70e03d7114695578dc170fe9be2338424b0cc20dbeffe9f503820016bee65f8c5de0c6388d56d78320a48e03a2cad7ad7
6
+ metadata.gz: f402f1244f5bb63082a52967e2d6c3baf19afaa9f7f4d0a7bc28da2888b53c3c40e37babdbbb935f5b1d30953f7bd85d91c2d0e0fc4efe2b141e16a3223af74c
7
+ data.tar.gz: a48e0845a7df3dd2f0dd6118390e3a4778c44b9320f80c87755dcf6f975e7652d3add44d0a4f0ef84ac9fcb82e5a52966af395e6ed292974c41edc7693d7e419
data/.rubocop.yml CHANGED
@@ -1,5 +1,6 @@
1
1
  AllCops:
2
2
  TargetRubyVersion: 2.7
3
+ NewCops: enable
3
4
 
4
5
  Style/StringLiterals:
5
6
  Enabled: true
@@ -21,7 +22,7 @@ Metrics/MethodLength:
21
22
  Metrics/AbcSize:
22
23
  Max: 35
23
24
 
24
- Metrics/Metrics/CyclomaticComplexity:
25
+ Metrics/CyclomaticComplexity:
25
26
  Max: 10
26
27
 
27
28
  Metrics/PerceivedComplexity:
data/CHANGELOG.md CHANGED
@@ -1,5 +1,129 @@
1
1
  ## [Released]
2
2
 
3
+ ## [1.2.0] - 2026-11-28
4
+
5
+ ### Added
6
+ - **`redirect_uri` option**: Overrides the callback URL sent to the provider in the authorization and token requests, which otherwise defaults to `<request base url>/auth/<name>/callback`. Useful behind proxies that change the host or scheme, or when the registered callback URL differs from the request host. The value must be an absolute `http` or `https` URL without a fragment; anything else fails the login with the `configuration_error` key. A warning is logged when its path does not match the strategy's `callback_path`, because OmniAuth would then not handle the provider's redirect.
7
+
8
+ ### Fixed
9
+ - **Authorization parameters are no longer sent twice**: OmniAuth stores `extra_authorize_params` with string keys, so a configured parameter that the strategy also sets (such as `prompt` or `redirect_uri`) was added a second time instead of replacing the strategy's value. Configured parameters now replace it. Parameters listed in `allow_authorize_params` as strings could likewise add a second `state`, `nonce` or other built-in parameter from the request; they can now only add parameters the strategy and `extra_authorize_params` do not set.
10
+ - **`redirect_uri` in `extra_authorize_params` is ignored**: It was sent alongside the gem's own value, and the token request still used the gem's value. A warning now points to the `redirect_uri` option.
11
+
12
+ ## [1.1.0] - 2026-10-14
13
+
14
+ ### Security
15
+ - **ID token algorithm no longer taken from the token header**: Previously, with `client_signing_alg` unset (the default), the gem verified an ID token with whatever algorithm its own header named. An unsigned `alg: none` token was accepted, which allowed forging a login for any `sub` in the `response_type: "id_token"` flow. Accepted algorithms now come from `client_signing_alg`, otherwise the discovery document's `id_token_signing_alg_values_supported`, otherwise `RS256`. `none` is always rejected. Raises `OmniauthOidc::InvalidAlgorithmError`.
16
+ - **Empty HMAC secret refused**: A `jwt_secret_base64` that decodes to an empty string is rejected with `OmniauthOidc::ConfigurationError` instead of being used as the HS256/384/512 key (CVE-2026-45363).
17
+ - **jwt dependency**: Now requires `jwt >= 2.10.3` and excludes 3.0.0 to 3.1.2, the releases affected by CVE-2026-45363.
18
+ - **Nonce read from session only**: The expected nonce is no longer taken from the callback's request params, which the caller controls. It now comes only from the value stored in the session during the request phase. This also removes a call to ActiveSupport's `presence`, which raised `NoMethodError` in non-Rails apps.
19
+ - **Nonce required when one was sent**: With `send_nonce: true` (the default), a callback whose session holds no nonce now fails with `OmniauthOidc::InvalidNonceError` instead of skipping the check. The `response_type: "id_token"` flow always sends and requires a nonce, as OIDC Core 3.2.2.1 requires. The nonce is consumed before any other claim check, so it stays single use even when verification fails, and its value is no longer written to error messages.
20
+ - **PKCE verifier read from session only**: The `code_verifier` is no longer taken from callback request params. With PKCE on, a callback whose session holds no verifier fails with `OmniauthOidc::TokenError`.
21
+ - **Issuer check cannot be skipped**: A discovery document with a missing or `null` `issuer` previously disabled the `iss` check (or crashed with `NoMethodError`). Discovery documents without `issuer` or `authorization_endpoint` are now rejected with `OmniauthOidc::ConfigurationError`.
22
+ - **`exp` claim required**: ID tokens without an `exp` claim, or with a non-numeric one, are now rejected with `OmniauthOidc::TokenVerificationError`, as OIDC Core 3.1.3.7 requires.
23
+ - **UserInfo `sub` must match the ID token**: A UserInfo response whose `sub` differs from the ID token's is ignored, and the login uses the ID token claims only (OIDC Core 5.3.4).
24
+ - **Login without a subject fails**: A callback that cannot determine a `sub` now fails with `OmniauthOidc::TokenVerificationError` instead of completing with a `nil` uid.
25
+ - **Safer HTTP redirects**: Redirects from HTTPS to HTTP are refused, and the `Authorization` header is dropped when a redirect leaves the original host, so a UserInfo access token cannot leak to another host or over cleartext.
26
+
27
+ ### Changed
28
+ - **PKCE is enabled by default** (`pkce: true`). Authorization servers that do not support PKCE ignore the extra parameters (RFC 6749 3.1). Set `pkce: false` to opt out.
29
+ - **Discovery document cached across requests**: OmniAuth copies the strategy for every request, so the discovery document was fetched on every request and callback. It is now cached per process for `discovery_cache_ttl` seconds (default `3600`, `0` disables). Failed fetches are not cached.
30
+ - **Concurrent cache access**: The JWKS cache no longer holds a global lock during network fetches. A slow JWKS endpoint for one provider no longer blocks cache hits for every other provider, and concurrent misses for the same URI trigger a single fetch.
31
+ - **HTTP timeouts**: Requests to the provider now time out after 5 seconds to connect and 10 seconds to read, instead of the 60 second `Net::HTTP` defaults.
32
+ - **Fewer signature checks**: The ID token is verified once per callback and the result is reused, instead of being decoded and verified up to three times.
33
+ - **Configuration and JWKS errors no longer return 500**: `OmniauthOidc::ConfigurationError` and `OmniauthOidc::JwksError` raised during the request or callback phase are passed to OmniAuth's failure handler with the `configuration_error` or `jwks_error` key.
34
+
35
+ ### Added
36
+ - **`clock_skew_leeway` option** (default `60` seconds): Tolerates clock drift between the app and the provider when checking the ID token `exp` and `nbf` claims. Set to `0` for the previous strict behavior. Values other than a non-negative Integer raise `OmniauthOidc::ConfigurationError`.
37
+ - **`discovery_cache_ttl` option** (default `3600` seconds).
38
+
39
+ ### Fixed
40
+ - **`jwks_cache_ttl` was ignored**: The option is now applied to the JWKS cache.
41
+ - **Signing key rotation**: An ID token whose `kid` is not in the cached JWKS now triggers a JWKS refresh, rate limited to once per minute per JWKS URI. Previously the refresh path never ran, and logins failed until the cache expired.
42
+ - **Missing `code` or `id_token` in the callback**: The failure response is now returned immediately, instead of being discarded while the callback continued to the token endpoint.
43
+ - **Discovery documents without optional fields**: A missing `userinfo_endpoint`, `end_session_endpoint` or `scopes_supported` no longer raises `NoMethodError`.
44
+
45
+ ### Deprecated
46
+ - **`uid_field` option**: It has never had an effect. The uid has always been the `sub` claim, the only identifier OIDC guarantees to be stable and unique per issuer, and that does not change. Setting `uid_field` to anything other than `"sub"` now logs a deprecation warning. The option will be removed in 2.0.0.
47
+
48
+ ### Upgrade notes
49
+ - Logins that are in progress during the upgrade (request phase on 1.0.x, callback on 1.1.0) fail once, because the session holds no PKCE verifier. Users can simply sign in again.
50
+ - Apps that set `require_state: false` to accept IdP-initiated logins also need `send_nonce: false`, since no nonce is stored for a login the app did not start.
51
+ - If a provider signs ID tokens with an algorithm it does not advertise in its discovery document, set `client_signing_alg` explicitly.
52
+
53
+ ## [1.0.1] - 2026-03-23
54
+
55
+ - Update jwt dependency
56
+
57
+ ## [1.0.0] - 2026-03-02
58
+
59
+ ### BREAKING CHANGES
60
+ - **Dependency Replacement**: Removed `openid_connect`, `openid_config_parser`, `json-jwt`, and `httparty` runtime dependencies. Replaced with custom `Net::HTTP`-based implementation and the standard `jwt` gem. Any code that relied on these gems being transitively available will need to add them directly.
61
+ - **Internal Object Types Changed**: Response objects are now custom classes instead of OpenIDConnect library types:
62
+ - `OpenIDConnect::Client` replaced by `OmniauthOidc::Client`
63
+ - `OpenIDConnect::ResponseObject::IdToken` replaced by `OmniauthOidc::ResponseObjects::IdToken`
64
+ - `OpenIDConnect::ResponseObject::UserInfo` replaced by `OmniauthOidc::ResponseObjects::UserInfo`
65
+ - `Rack::OAuth2::AccessToken` replaced by `OmniauthOidc::ResponseObjects::AccessToken`
66
+ - **Session Keys Namespaced**: Session keys now include the provider name (e.g. `omniauth.my_provider.state` instead of `omniauth.state`). This enables multiple OIDC providers but breaks code that manually accesses session keys with the old format. Users mid-authentication during upgrade will see state mismatch errors.
67
+ - **Scope Return Type**: `scope` now returns a space-delimited String (e.g. `"openid profile email"`) instead of an Array. Code that called `.each`, `.include?`, or other Array methods on the return value will break.
68
+ - **AuthHash Construction**: Now uses OmniAuth DSL blocks (`info`, `credentials`, `extra`) consistently instead of manually building `env["omniauth.auth"]`. The `info` hash now includes all standard OIDC UserInfo fields (given_name, family_name, gender, picture, phone, website).
69
+ - **Error Classes Restructured**: Error handling uses new specific error classes under `OmniauthOidc::` namespace. `Rack::OAuth2::Client::Error` is no longer caught. `validate_client_algorithm!` now raises `OmniauthOidc::InvalidAlgorithmError` instead of `CallbackError`.
70
+ - **CallbackError Parameter Names**: `CallbackError` now accepts `error_reason:` and `error_uri:` keyword arguments (previously `reason:` and `uri:`). The old keys are still accepted for backward compatibility.
71
+
72
+ ### Added
73
+ - **Custom HTTP Client** (`OmniauthOidc::HttpClient`): Net::HTTP-based client for all HTTP requests, removing external HTTP client dependencies entirely
74
+ - GET requests follow up to 5 redirects (301, 302, 307, 308), including relative redirects
75
+ - POST requests reject redirects to prevent credential leakage
76
+ - **Custom OIDC Client** (`OmniauthOidc::Client`): Handles authorization URI construction, token exchange, and userinfo fetching
77
+ - **Response Objects** (`OmniauthOidc::ResponseObjects`): `IdToken`, `UserInfo`, and `AccessToken` classes with method-style access to standard OIDC claims
78
+ - **Configuration Fetcher** (`OmniauthOidc::ConfigFetcher`): Fetches and parses `.well-known/openid-configuration` with retry support
79
+ - **JWK Handler** (`OmniauthOidc::JwkHandler`): JWKS parsing with proper `kid`-based key selection for providers that publish multiple signing keys (e.g. Google, Microsoft Entra ID, Auth0)
80
+ - **JWKS Caching** (`OmniauthOidc::JwksCache`): Thread-safe JWKS cache with configurable TTL (default 1 hour)
81
+ - Automatic cache invalidation and retry on signature verification failure
82
+ - Manual cache control via `OmniauthOidc::JwksCache.clear!` and `.invalidate(uri)`
83
+ - Configurable via `jwks_cache_ttl` option
84
+ - **Logging & Instrumentation** (`OmniauthOidc::Logging`): Logging via Ruby Logger with optional ActiveSupport::Notifications integration
85
+ - Configurable log levels (default: WARN)
86
+ - Automatic sanitization of sensitive data (tokens, secrets, code verifiers)
87
+ - Event instrumentation for config fetch, token exchange, userinfo fetch, JWKS fetch, request phase, and callback phase
88
+ - **Error Hierarchy**: Specific error classes for all failure modes
89
+ - `TokenVerificationError`, `TokenExpiredError`, `InvalidAlgorithmError`, `InvalidSignatureError`
90
+ - `InvalidIssuerError`, `InvalidAudienceError`, `InvalidNonceError`
91
+ - `JwksFetchError`, `KeyNotFoundError`
92
+ - `ConfigurationError`, `MissingConfigurationError`
93
+ - **Configuration Validation**: Required options (`identifier`, `secret`, `config_endpoint`) are validated on first request with a clear error message listing all missing fields
94
+ - **RBS Type Signatures** (`sig/omniauth_oidc.rbs`): Full type declarations for all public API classes
95
+ - **Comprehensive Test Suite**: Unit tests for HTTP client, JWK handler, JWKS cache, logging, errors, and strategy configuration
96
+
97
+ ### Fixed
98
+ - **JWK kid Selection**: `keyset_for_algorithm` now selects the correct signing key by `kid` from JWKS. Previously, with multiple keys in the JWKS, verification could fail or use the wrong key.
99
+ - **Dead Code Removed**: Removed `decode` method in Verify module that referenced undefined `UrlSafeBase64` constant
100
+ - **Typo**: Fixed `client_singing_alg` to `client_signing_alg` in error messages
101
+ - **Scope Default**: Fixed default scope fallback from `[:open_id]` (typo) to `[:openid]`
102
+ - **AuthHash Consistency**: Consolidated duplicate user info fetching and AuthHash construction into OmniAuth DSL blocks
103
+ - **Removed `resolve_endpoint_from_host`**: Endpoints are now used as full URLs from the discovery document instead of being stripped to relative paths
104
+
105
+ ### Changed
106
+ - **Module Loading**: Replaced `Dir.glob` with explicit `require_relative` for clarity and predictable load order
107
+ - **Dependency Constraints**: Runtime dependencies reduced to `omniauth ~> 2.1` and `jwt ~> 2.7`
108
+ - **CI Updates**: Added Ruby 4.0.1 to test matrix, updated `actions/checkout` to v6, RuboCop runs on Ruby 3.3
109
+ - **RuboCop Config**: Fixed invalid cop name `Metrics/Metrics/CyclomaticComplexity`, added `NewCops: enable`
110
+
111
+ ### Migration Guide from 0.x to 1.0.0
112
+
113
+ 1. **Dependencies**: Remove gems that were only used by this gem, then run `bundle install`:
114
+ - `httparty`
115
+ - `openid_connect`
116
+ - `openid_config_parser`
117
+ - `json-jwt`
118
+ 2. **Session Keys**: If you manually access session keys, update to the new namespaced format: `omniauth.{provider_name}.state`, `omniauth.{provider_name}.nonce`.
119
+ 3. **Scope Handling**: If your code treats `scope` as an Array, update it. `scope` now returns a space-delimited String.
120
+ 4. **Error Handling**: Update rescue clauses to catch the new error classes if needed. For example:
121
+ - `Rack::OAuth2::Client::Error` -> `OmniauthOidc::TokenError`
122
+ - Algorithm mismatches now raise `OmniauthOidc::InvalidAlgorithmError` instead of `CallbackError`
123
+ 5. **Response Objects**: If you access `access_token` or `user_info` objects directly, note they are now `OmniauthOidc::ResponseObjects::AccessToken` and `OmniauthOidc::ResponseObjects::UserInfo` respectively.
124
+ 6. **Logging** (optional): Configure logging level: `OmniauthOidc::Logging.log_level = Logger::INFO`
125
+ 7. **Ruby 4.0+**: Add `gem "ostruct"` to your Gemfile (removed from default gems in Ruby 4.0).
126
+
3
127
  ## [0.2.7] - 2024-10-11
4
128
  - Dependencies update
5
129
 
data/LICENSE.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2024 Suleyman Musayev
3
+ Copyright (c) 2024-present Suleyman Musayev
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
data/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # OmniAuth::Oidc
2
2
 
3
- This gem provides an OmniAuth strategy for integrating OpenID Connect (OIDC) authentication into your Ruby on Rails application. It allows seamless login using various OIDC providers.
3
+ OmniAuth strategy for OpenID Connect (OIDC) authentication. Supports multiple OIDC providers, PKCE, JWKS key rotation, and both `code` and `id_token` response types.
4
+
5
+ Minimal dependencies: only `omniauth` and `jwt` gems required. All HTTP requests use Ruby's built-in `Net::HTTP`, with no Faraday, HTTParty, or other external HTTP clients.
4
6
 
5
7
  Developed with reference to [omniauth-openid-connect](https://github.com/jjbohn/omniauth-openid-connect) and [omniauth_openid_connect](https://github.dev/omniauth/omniauth_openid_connect).
6
8
 
@@ -16,14 +18,15 @@ If bundler is not being used to manage dependencies, install the gem by executin
16
18
 
17
19
  $ gem install omniauth_oidc
18
20
 
21
+ **Ruby 4.0+**: Add `gem "ostruct"` to your Gemfile (`ostruct` was removed from default gems in Ruby 4.0).
19
22
 
20
23
  ## Usage
21
24
 
22
25
  To use the OmniAuth OIDC strategy, you need to configure your Rails application and set up the necessary environment variables for OIDC client credentials.
23
26
 
24
27
  ### Configuration
25
- You have to provide Client ID, Client Secret and url for the OIDC configuration endpoint as a bare minimum for the `omniauth_oidc` to work properly.
26
- Create an initializer file at `config/initializers/omniauth.rb`
28
+
29
+ You must provide Client ID, Client Secret, and the URL for the OIDC configuration endpoint as a minimum for `omniauth_oidc` to work. Create an initializer file at `config/initializers/omniauth.rb`:
27
30
 
28
31
  ```ruby
29
32
  # config/initializers/omniauth.rb
@@ -39,15 +42,14 @@ Rails.application.config.middleware.use OmniAuth::Builder do
39
42
  end
40
43
  ```
41
44
 
42
- With Devise
45
+ With Devise:
43
46
 
44
47
  ```ruby
45
48
  Devise.setup do |config|
46
49
  config.omniauth :oidc, {
47
50
  name: :simple_provider,
48
- scope: [:openid, :email, :profile, :address],
51
+ scope: %w[openid email profile address],
49
52
  response_type: :code,
50
- uid_field: "preferred_username",
51
53
  client_options: {
52
54
  identifier: '23575f4602bebbd9a17dbc38d85bd1a77',
53
55
  secret: ENV['SIMPLE_PROVIDER_CLIENT_SECRET'],
@@ -57,7 +59,7 @@ Devise.setup do |config|
57
59
  end
58
60
  ```
59
61
 
60
- The gem also supports a wide range of optional parameters for higher degree of configurability.
62
+ The gem also supports a wide range of optional parameters for a higher degree of configurability:
61
63
 
62
64
  ```ruby
63
65
  # config/initializers/omniauth.rb
@@ -65,33 +67,35 @@ Rails.application.config.middleware.use OmniAuth::Builder do
65
67
  provider :oidc, {
66
68
  name: :complex_provider, # used for dynamic routing
67
69
  issuer: 'https://complexprovider.com/cdn-cgi/access/sso/oidc/23575f4602bebbd9a17dbc38d85bd1a77',
68
- scope: [:openid],
70
+ scope: %w[openid],
69
71
  response_type: 'id_token',
70
72
  require_state: true,
71
73
  response_mode: :query,
72
74
  prompt: :login,
73
- send_nonce: false,
74
- uid_field: "sub",
75
- pkce: false,
75
+ send_nonce: true, # always on for response_type 'id_token'
76
+ pkce: true, # default since 1.1.0
77
+ jwks_cache_ttl: 3600, # JWKS cache TTL in seconds (default: 3600)
78
+ discovery_cache_ttl: 3600, # Discovery document cache TTL in seconds (default: 3600)
79
+ clock_skew_leeway: 60, # Allowed clock drift in seconds for exp/nbf (default: 60)
76
80
  client_options: {
77
81
  identifier: '23575f4602bebbd9a17dbc38d85bd1a77',
78
82
  secret: ENV['COMPLEX_PROVIDER_CLIENT_SECRET'],
79
83
  config_endpoint: 'https://complexprovider.com/cdn-cgi/access/sso/oidc/23575f4602bebbd9a17dbc38d85bd1a77/.well-known/openid-configuration',
80
- host: 'complexprovider.com'
84
+ host: 'complexprovider.com',
81
85
  scheme: "https",
82
86
  port: 443,
83
87
  authorization_endpoint: 'https://complexprovider.com/cdn-cgi/access/sso/oidc/23575f4602bebbd9a17dbc38d85bd1a77/authorization',
84
88
  token_endpoint: 'https://complexprovider.com/cdn-cgi/access/sso/oidc/23575f4602bebbd9a17dbc38d85bd1a77/token',
85
89
  userinfo_endpoint: 'https://complexprovider.com/cdn-cgi/access/sso/oidc/23575f4602bebbd9a17dbc38d85bd1a77/userinfo',
86
90
  jwks_uri: 'https://complexprovider.com/cdn-cgi/access/sso/oidc/23575f4602bebbd9a17dbc38d85bd1a77/jwks',
87
- end_session_endpoint: '/signout'
91
+ end_session_endpoint: 'https://complexprovider.com/signout'
88
92
  }
89
93
  }
90
94
  end
91
95
  ```
92
96
 
93
- Ensure to replace identifier, secret, configuration endpoint url and others with credentials received from your OIDC provider.
94
- Please note that the gem does not accept `redirect_uri` as a configurable option. For details please see section Routes.
97
+ Ensure to replace identifier, secret, configuration endpoint URL and others with credentials received from your OIDC provider.
98
+ By default the gem builds the `redirect_uri` dynamically from the request. You can override it with the `redirect_uri` option. For details please see section Routes.
95
99
 
96
100
  ### Redirecting for Authentication
97
101
 
@@ -103,7 +107,7 @@ Buttons and links to initialize the authentication request can be placed on rele
103
107
 
104
108
  ### Handling Callbacks
105
109
 
106
- The gem uses dyanmic routes to handle different phases, and while you can use same routes in your Rails application, for
110
+ The gem uses dynamic routes to handle different phases, and while you can use same routes in your Rails application, for
107
111
  better experience you should have a controller to process the authenticated user. Create a CallbacksController:
108
112
 
109
113
  ```ruby
@@ -113,9 +117,9 @@ class CallbacksController < ApplicationController
113
117
  # user info received from OIDC provider will be available in `request.env['omniauth.auth']`
114
118
  auth = request.env['omniauth.auth']
115
119
 
116
- user = User.find_or_create_by(uid: auth['uid']) do |user|
117
- user.name = auth['info']['name']
118
- user.email = auth['info']['email']
120
+ user = User.find_or_create_by(uid: auth['uid']) do |u|
121
+ u.name = auth['info']['name']
122
+ u.email = auth['info']['email']
119
123
  end
120
124
 
121
125
  session[:user_id] = user.id
@@ -124,17 +128,74 @@ class CallbacksController < ApplicationController
124
128
  end
125
129
  ```
126
130
 
131
+ The `omniauth.auth` hash includes:
132
+
133
+ ```ruby
134
+ {
135
+ provider: :simple_provider,
136
+ uid: "user123",
137
+ info: {
138
+ name: "Test User",
139
+ email: "test@example.com",
140
+ email_verified: true,
141
+ nickname: "testuser", # preferred_username
142
+ first_name: "Test", # given_name
143
+ last_name: "User", # family_name
144
+ gender: "male",
145
+ image: "https://example.com/avatar.jpg", # picture
146
+ phone: "+1234567890", # phone_number
147
+ urls: { website: "https://testuser.com" }
148
+ },
149
+ credentials: {
150
+ id_token: "eyJ...",
151
+ token: "access_token_value",
152
+ refresh_token: "refresh_token_value",
153
+ expires_in: 3600,
154
+ scope: "openid profile email"
155
+ },
156
+ extra: {
157
+ raw_info: { ... } # full userinfo response attributes
158
+ }
159
+ }
160
+ ```
161
+
127
162
  ### Routes
128
163
 
129
- The gem uses dynamic routes when making requests to the OIDC provider endpoints, so called `redirect_uri` which is a
130
- non-configurable value that follows the naming pattern of `https://your_app.com/auth/<simple_provider>/callback`,
164
+ The gem uses dynamic routes when making requests to the OIDC provider endpoints, so called `redirect_uri` which by
165
+ default follows the naming pattern of `https://your_app.com/auth/<simple_provider>/callback`,
131
166
  where `<simple_provider>` is the provider name defined within the configuration of the `omniauth.rb` initializer.
132
167
  This represents the `redirect_uri` that will be passed with the authorization request to your OIDC provider and that
133
168
  has to be registered with your OIDC provider as permitted `redirect_uri`.
134
169
 
170
+ If the URL your OIDC provider must redirect to differs from the one built from the request (for example, behind a
171
+ proxy or load balancer that changes the host or scheme, or when one callback URL is registered for several hosts), set
172
+ the `redirect_uri` option. The same value is sent in the authorization request and in the token request:
173
+
174
+ ```ruby
175
+ provider :oidc, {
176
+ name: :simple_provider,
177
+ redirect_uri: "https://your_app.com/auth/simple_provider/callback",
178
+ client_options: { ... }
179
+ }
180
+ ```
181
+
182
+ Keep the following in mind when setting `redirect_uri`:
183
+
184
+ - It must be an absolute `http` or `https` URL without a fragment. Any other value fails the login with the
185
+ `configuration_error` key.
186
+ - Its path must match the strategy's `callback_path` (by default `/auth/<name>/callback`). OmniAuth only handles the
187
+ provider's redirect on that path, so if they differ the redirect reaches your app without being authenticated. The gem
188
+ logs a warning when they do not match. Set `callback_path` to the same path if you change it.
189
+ - The request phase stores the `state`, nonce and PKCE verifier in the session. If `redirect_uri` points to a different
190
+ host than the one the login started on, the browser must send the same session cookie there. Otherwise the callback
191
+ fails with `csrf_detected` or `token_error`. Scope the session cookie to a shared parent domain (for example
192
+ `domain: ".your_app.com"`) when one callback URL serves several hosts.
193
+ - If you previously set `redirect_uri` in `extra_authorize_params` as a workaround, move it to this option. A
194
+ `redirect_uri` in `extra_authorize_params` is now ignored, and the gem logs a warning.
195
+
135
196
  Dynamic routes are used to process responses and perform intermediary steps by the middleware, e.g. request phase,
136
- token verification. While you can define and use same routes within your Rails app, it is highly recommended to modify
137
- your `routes.rb` to perform a dynamic redirect to a another controller method so this does not cause any conflicts with
197
+ token verification. While you can define and use same routes within your Rails app, it is highly recommended to modify
198
+ your `routes.rb` to perform a dynamic redirect to another controller method so this does not cause any conflicts with
138
199
  the middleware or the authorization flow.
139
200
 
140
201
  In an example below, `auth/:provider/callback` is generalized `redirect_uri` value that is passed in the authorization
@@ -163,11 +224,11 @@ end
163
224
  ```
164
225
 
165
226
  **Please note that you should register `https://your_app.com/auth/<simple_provider>/callback` with your OIDC provider
166
- as a callback redirect url.**
227
+ as a callback redirect URL.**
167
228
 
168
229
  ### Using Access Token Without User Info
169
230
 
170
- In case your app requries only an access token and not the user information, then you can specify an optional
231
+ In case your app requires only an access token and not the user information, then you can specify an optional
171
232
  configuration in the omniauth initializer:
172
233
 
173
234
  ```ruby
@@ -185,38 +246,17 @@ Rails.application.config.middleware.use OmniAuth::Builder do
185
246
  end
186
247
  ```
187
248
 
188
- Then the callback returned once your user authenticates with the OIDC provider will contain only access token parameters:
189
-
190
- ```ruby
191
- # app/controllers/callbacks_controller.rb
192
- class CallbacksController < ApplicationController
193
- def omniauth
194
- # access token parameters received from OIDC provider will be available in `request.env['omniauth.auth']`
195
- omniauth_params = request.env['omniauth.auth']
196
-
197
- # omniauth_params will contain similar data as shown below
198
- # {"provider"=>:simple_provider_access_token_only,
199
- # "credentials"=>
200
- # {"id_token"=> "id token value",
201
- # "token"=> "token value",
202
- # "refresh_token"=>"refresh token value",
203
- # "expires_in"=>300,
204
- # "scope"=>nil
205
- # }
206
- # }
207
- end
208
- end
209
- ```
249
+ When `fetch_user_info` is `false`, user info is extracted from the ID token claims instead of calling the userinfo endpoint. If the userinfo endpoint call fails, the gem also falls back to ID token claims automatically.
210
250
 
211
251
  ### Ending Session
212
252
 
213
253
  The gem provides two configuration options to allow ending a session simultaneously with your client application and the
214
254
  OIDC provider.
215
255
 
216
- To use this feature, you need to provide a `logout_path` in the options and an `end_session_endpoint` in the client
217
- options. Here’s a sample setup:
256
+ To use this feature, you need to provide a `logout_path` in the options and an `end_session_endpoint` in the client
257
+ options. Here's a sample setup:
218
258
 
219
- ``` ruby
259
+ ```ruby
220
260
  provider :oidc, {
221
261
  name: :simple_provider,
222
262
  client_options: {
@@ -236,42 +276,117 @@ options. Here’s a sample setup:
236
276
  Using these two configurations, you can ensure that when a user logs out from your application, they are also logged out
237
277
  from the OIDC provider, providing a seamless logout across multiple services.
238
278
 
239
- This works by calling `other_phase` on every controller request in your application. The method checks if the requested
240
- URL matches the defined `logout_path`. If it does (i.e. current user has requested to log out from your application)
241
- `other_phase` performs a redirect to the `end_session_endpoint` to terminate the user's session with the OIDC provider
279
+ This works by calling `other_phase` on every controller request in your application. The method checks if the requested
280
+ URL matches the defined `logout_path`. If it does (i.e. current user has requested to log out from your application)
281
+ `other_phase` performs a redirect to the `end_session_endpoint` to terminate the user's session with the OIDC provider
242
282
  and then it returns back to your application and concludes the request to end the current user's session.
243
283
 
244
284
  For additional details please refer to the [OIDC specification](https://openid.net/specs/openid-connect-session-1_0-17.html#:~:text=%C2%A0TOC-,5.%C2%A0%20RP%2DInitiated%20Logout,-An%20RP%20can).
245
285
 
286
+ ### Logging
287
+
288
+ The gem includes built-in logging with automatic sensitive data sanitization. By default, log level is set to WARN.
289
+
290
+ ```ruby
291
+ # Set log level
292
+ OmniauthOidc::Logging.log_level = Logger::INFO
293
+
294
+ # Use a custom logger
295
+ OmniauthOidc::Logging.logger = Rails.logger
296
+ ```
297
+
298
+ If ActiveSupport::Notifications is available (e.g. in Rails), the gem publishes instrumentation events:
299
+
300
+ - `config.fetch.omniauth_oidc`: OIDC discovery document fetch
301
+ - `token.exchange.omniauth_oidc`: authorization code to token exchange
302
+ - `userinfo.fetch.omniauth_oidc`: userinfo endpoint call
303
+ - `jwks.fetch.omniauth_oidc`: JWKS fetch
304
+ - `request_phase.start.omniauth_oidc`: authorization redirect
305
+ - `callback_phase.start.omniauth_oidc`: callback processing
306
+ - `id_token.verify.omniauth_oidc`: ID token verification
307
+
308
+ ### Error Handling
309
+
310
+ The gem raises specific error classes that you can rescue in your callback handling:
311
+
312
+ | Error Class | When Raised |
313
+ |---|---|
314
+ | `OmniauthOidc::MissingConfigurationError` | Required options (`identifier`, `secret`, `config_endpoint`) are missing |
315
+ | `OmniauthOidc::ConfigurationError` | OIDC discovery endpoint fetch fails, the discovery document has no `issuer` or `authorization_endpoint`, or an option is invalid (negative `clock_skew_leeway`, empty HMAC secret) |
316
+ | `OmniauthOidc::TokenError` | Token exchange fails, or PKCE is enabled and no code verifier is stored in the session |
317
+ | `OmniauthOidc::TokenVerificationError` | JWT format is invalid, the ID token has no numeric `exp` claim, or no subject (`sub`) could be determined |
318
+ | `OmniauthOidc::TokenExpiredError` | ID token `exp` claim is in the past, beyond `clock_skew_leeway` |
319
+ | `OmniauthOidc::InvalidAlgorithmError` | JWT algorithm is not accepted (see [Security Defaults](#security-defaults)) |
320
+ | `OmniauthOidc::InvalidSignatureError` | JWT signature verification fails |
321
+ | `OmniauthOidc::InvalidIssuerError` | ID token `iss` does not match expected issuer |
322
+ | `OmniauthOidc::InvalidAudienceError` | ID token `aud` does not match client identifier |
323
+ | `OmniauthOidc::InvalidNonceError` | ID token `nonce` does not match the stored nonce, or no nonce is stored when one is required |
324
+ | `OmniauthOidc::JwksFetchError` | JWKS endpoint fetch fails |
325
+
326
+ All error classes inherit from `OmniauthOidc::Error < RuntimeError`.
327
+
328
+ During the request and callback phases these errors do not propagate as exceptions. They are passed to OmniAuth's
329
+ failure handler, which by default redirects to `/auth/failure?message=<key>` with one of these keys: `csrf_detected`,
330
+ `missing_code`, `missing_id_token`, `token_error`, `http_error`, `timeout`, `failed_to_connect`, `configuration_error`
331
+ or `jwks_error`. The exception itself is available in `request.env['omniauth.error']`.
332
+
333
+ ### Security Defaults
334
+
335
+ The gem verifies every ID token as required by [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation):
336
+
337
+ - **Signature and algorithm**: the accepted algorithms come from configuration, never from the token header. They are
338
+ `client_signing_alg` when set, otherwise the provider's `id_token_signing_alg_values_supported`, otherwise `RS256`.
339
+ Unsigned (`alg: none`) tokens are always rejected, and an empty HMAC secret is refused.
340
+ - **Claims**: `iss` must equal the discovery `issuer`, `aud` must contain the client `identifier`, `exp` is required,
341
+ and `exp`/`nbf` allow `clock_skew_leeway` seconds of drift.
342
+ - **Nonce**: generated per login and stored in the session. It is required when `send_nonce` is on (the default) and
343
+ always for `response_type: 'id_token'`. It is never read from request parameters.
344
+ - **PKCE**: on by default. The code verifier is read only from the session.
345
+ - **UserInfo**: the response is used only when its `sub` matches the ID token `sub` (OIDC Core 5.3.4).
346
+ - **HTTP**: requests time out after 5s (connect) and 10s (read). Redirects never downgrade from HTTPS to HTTP, and the
347
+ `Authorization` header is dropped when a redirect leaves the original host.
348
+ - **Caching**: the discovery document and JWKS are cached per process. An ID token with an unknown `kid` triggers at
349
+ most one JWKS refresh per minute, so signing key rotation is picked up without letting forged tokens flood the
350
+ provider.
351
+
246
352
  ### Advanced Configuration
353
+
247
354
  You can customize the OIDC strategy further by adding additional configuration options:
248
355
 
249
356
  | Field | Description | Required | Default Value | Example/Notes |
250
357
  |------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|-------------------------------------|-------------------------------------------------------|
251
358
  | name | Arbitrary string to identify OIDC provider and segregate it from other OIDC providers | no | `"oidc"` | `:simple_provider` |
252
- | issuer | Root url for the OIDC authorization server | no | retrived from config_endpoint | `"https://simpleprovider.com"` |
253
- | fetch_user_info | Fetches user information from user_info_endpoint using the access token. If set to false the omniauth params will include only access token | no | `true` | `fetch_user_info: false` |
254
- | client_auth_method | Authentication method to be used with the OIDC authorization server | no | `:basic` | `"basic"`, `"jwks"` |
255
- | scope | OIDC scopes to be included in the server's response | `[:openid]` is required | all scopes offered by OIDC provider | `[:openid, :profile, :email]` |
359
+ | issuer | Root url for the OIDC authorization server | no | retrieved from config_endpoint | `"https://simpleprovider.com"` |
360
+ | fetch_user_info | Fetches user information from userinfo endpoint using the access token. If false, user info is extracted from ID token claims | no | `true` | `fetch_user_info: false` |
361
+ | client_signing_alg | Expected JWT signing algorithm. Tokens signed with any other algorithm are rejected | no | `nil` (provider-advertised, else RS256) | `"RS256"`, `"HS256"` |
362
+ | scope | OIDC scopes to request. Accepts Array or String; always sent as a space-delimited string | `openid` is required | all scopes offered by OIDC provider | `%w[openid profile email]` |
256
363
  | response_type | OAuth2 response type expected from OIDC provider during authorization | no | `"code"` | `"code"` or `"id_token"` |
257
364
  | state | Value to be used for the OAuth2 state parameter on the authorization request. Can be a proc that generates a string | no | Random 16 character string | `Proc.new { SecureRandom.hex(32) }` |
258
365
  | require_state | Boolean to indicate if state param should be verified. This is a recommendation by OIDC spec | no | `true` | `true` or `false` |
259
366
  | response_mode | The response mode per [OIDC spec](https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html) | no | `nil` | `:query`, `:fragment`, `:form_post` or `:web_message` |
260
367
  | display | Specifies how OIDC authorization server should display the authentication and consent UI pages to the end user | no | `nil` | `:page`, `:popup`, `:touch` or `:wap` |
261
368
  | prompt | Specifies whether the OIDC authorization server prompts the end user for reauthentication and consent | no | `nil` | `:none`, `:login`, `:consent` or `:select_account` |
369
+ | send_nonce | Include a nonce in the authorization request and require it in the ID token. Always on for `response_type: 'id_token'` | no | `true` | `true` or `false` |
262
370
  | send_scope_to_token_endpoint | Should the scope parameter be sent to the authorization token endpoint | no | `true` | `true` or `false` |
371
+ | redirect_uri | Callback URL sent to the OIDC provider in the authorization and token requests. Must be an absolute URL registered with the provider | no | `<request base url>/auth/<name>/callback` | `"https://your_app.com/auth/simple_provider/callback"` |
263
372
  | post_logout_redirect_uri | Logout redirect uri to use per the [session management draft](https://openid.net/specs/openid-connect-session-1_0.html) | no | `nil` | `"https://your_app.com/logout/callback"` |
264
- | uid_field | Field of the user info response to be used as a unique ID | no | `'sub'` | `"sub"` or `"preferred_username"` |
373
+ | uid_field | **Deprecated**, removed in 2.0.0. Has never had an effect: the uid is always the `sub` claim | no | `"sub"` | Remove from configuration |
265
374
  | extra_authorize_params | Hash of extra fixed parameters that will be merged to the authorization request | no | `{}` | `{"tenant" => "common"}` |
266
375
  | allow_authorize_params | List of allowed dynamic parameters that will be merged to the authorization request | no | `[]` | `[:screen_name]` |
267
- | pkce | Enable [PKCE flow](https://oauth.net/2/pkce/) | no | `false` | `true` or `false` |
376
+ | pkce | Enable [PKCE flow](https://oauth.net/2/pkce/) | no | `true` | `true` or `false` |
268
377
  | pkce_verifier | Specify custom PKCE verifier code | no | Random 128-character string | `Proc.new { SecureRandom.hex(64) }` |
269
- | pkce_options | Specify custom implementation of the PKCE code challenge/method | no | SHA256(code_challenge) in hex | Proc to customise the code challenge generation |
378
+ | pkce_options | Specify custom implementation of the PKCE code challenge/method | no | S256 (base64url SHA-256 of verifier) | Proc to customise the code challenge generation |
270
379
  | client_options | Hash of client options detailed below in a separate table | yes | see below | see below |
271
380
  | jwt_secret_base64 | Specify the base64-encoded secret used to sign the JWT token for HMAC with SHA2 (e.g. HS256) signing algorithms | no | `client_options.secret` | `"bXlzZWNyZXQ=\n"` |
272
- | logout_path | Log out is only triggered when the request path ends on this path | no | `'/logout'` | '/sign_out' |
273
- | acr_values | Authentication Class Reference (ACR) values to be passed to the authorize_uri to enforce a specific level, see [RFC9470](https://www.rfc-editor.org/rfc/rfc9470.html) | no | `nil` | `"c1 c2"` å|
274
-
381
+ | client_jwk_signing_key | JWK or JWKS (as JSON string or Hash) for local signature verification without fetching from `jwks_uri` | no | `nil` | `'{"kty":"RSA","n":"...","e":"AQAB"}'` |
382
+ | client_x509_signing_key | X.509 certificate (PEM format) for local signature verification | no | `nil` | PEM string |
383
+ | logout_path | Log out is only triggered when the request path ends on this path | no | `"/logout"` | `"/sign_out"` |
384
+ | jwks_cache_ttl | JWKS cache time-to-live in seconds, shared by all requests in the process | no | `3600` (1 hour) | `7200` |
385
+ | discovery_cache_ttl | Discovery document cache time-to-live in seconds, shared by all requests in the process | no | `3600` (1 hour) | `0` to disable |
386
+ | clock_skew_leeway | Seconds of clock drift allowed when checking the ID token `exp` and `nbf` claims | no | `60` | `0` to disable |
387
+ | hd | Google-specific: hosted domain parameter | no | `nil` | `"example.com"` |
388
+ | max_age | Maximum authentication age in seconds | no | `nil` | `3600` |
389
+ | acr_values | Authentication Class Reference (ACR) values per [RFC9470](https://www.rfc-editor.org/rfc/rfc9470.html) | no | `nil` | `"c1 c2"` |
275
390
 
276
391
  Below are options for the `client_options` hash of the configuration:
277
392
 
@@ -280,14 +395,14 @@ Below are options for the `client_options` hash of the configuration:
280
395
  | identifier | OAuth2 client_id | yes | `nil` |
281
396
  | secret | OAuth2 client secret | yes | `nil` |
282
397
  | config_endpoint | OIDC configuration endpoint | yes | `nil` |
283
- | scheme | http scheme to use | no | https |
284
- | host | host of the authorization server | no | nil |
285
- | port | port for the authorization server | no | 443 |
286
- | authorization_endpoint | authorize endpoint on the authorization server | no | retrived from config_endpoint |
287
- | token_endpoint | token endpoint on the authorization server | no | retrived from config_endpoint |
288
- | userinfo_endpoint | user info endpoint on the authorization server | no | retrived from config_endpoint |
289
- | jwks_uri | jwks_uri on the authorization server | no | retrived from config_endpoint |
290
- | end_session_endpoint | url to call to log the user out at the authorization server | no | `nil` |
398
+ | scheme | HTTP scheme to use | no | `"https"` |
399
+ | host | Host of the authorization server | no | `nil` |
400
+ | port | Port for the authorization server | no | `443` |
401
+ | authorization_endpoint | Authorize endpoint on the authorization server | no | retrieved from config_endpoint |
402
+ | token_endpoint | Token endpoint on the authorization server | no | retrieved from config_endpoint |
403
+ | userinfo_endpoint | User info endpoint on the authorization server | no | retrieved from config_endpoint |
404
+ | jwks_uri | JWKS URI on the authorization server | no | retrieved from config_endpoint |
405
+ | end_session_endpoint | URL to call to log the user out at the authorization server | no | `nil` |
291
406
 
292
407
  ## Contributing
293
408