omniauth_oidc 0.2.7 → 1.1.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: e94e09a2103532e642e008b239bf772fab6a609e9a9fcde6b943687b89ee25d9
4
+ data.tar.gz: e22f3910b293c1e4fcf9ea3746a27bf8258764b697acd2dd3fe7bce8425cb16c
5
5
  SHA512:
6
- metadata.gz: d48453b68849c0ec1a34a0d58805efb3a1cecbb4966d40e0ba4098d679330cf5d7f27b401e9a6a2d6d4f4bae4dc36224bb5b0788299358e6a8054b1c35666996
7
- data.tar.gz: b7dfad42cf0c15f34d36ce0676e79da70e03d7114695578dc170fe9be2338424b0cc20dbeffe9f503820016bee65f8c5de0c6388d56d78320a48e03a2cad7ad7
6
+ metadata.gz: 0a26fcaae36be1ba4f3f5b0f69e97e5528e0dd041fe29add4bbcede7b84ddf8377222c9a3dc7c8af6da53218a7acbb1e0183e816cc848b974247fc82e3c2e4dc
7
+ data.tar.gz: 3c1cbe6e6ce3c57b028c59346614719424693b894d018eccb8708d6e2ec621ef63870571a40b96cf487e26da1fb1c3afc3f5578329155e6832fdd4518fe79613
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,120 @@
1
1
  ## [Released]
2
2
 
3
+ ## [1.1.0] - 2026-10-14
4
+
5
+ ### Security
6
+ - **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`.
7
+ - **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).
8
+ - **jwt dependency**: Now requires `jwt >= 2.10.3` and excludes 3.0.0 to 3.1.2, the releases affected by CVE-2026-45363.
9
+ - **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.
10
+ - **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.
11
+ - **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`.
12
+ - **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`.
13
+ - **`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.
14
+ - **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).
15
+ - **Login without a subject fails**: A callback that cannot determine a `sub` now fails with `OmniauthOidc::TokenVerificationError` instead of completing with a `nil` uid.
16
+ - **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.
17
+
18
+ ### Changed
19
+ - **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.
20
+ - **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.
21
+ - **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.
22
+ - **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.
23
+ - **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.
24
+ - **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.
25
+
26
+ ### Added
27
+ - **`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`.
28
+ - **`discovery_cache_ttl` option** (default `3600` seconds).
29
+
30
+ ### Fixed
31
+ - **`jwks_cache_ttl` was ignored**: The option is now applied to the JWKS cache.
32
+ - **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.
33
+ - **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.
34
+ - **Discovery documents without optional fields**: A missing `userinfo_endpoint`, `end_session_endpoint` or `scopes_supported` no longer raises `NoMethodError`.
35
+
36
+ ### Deprecated
37
+ - **`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.
38
+
39
+ ### Upgrade notes
40
+ - 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.
41
+ - 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.
42
+ - If a provider signs ID tokens with an algorithm it does not advertise in its discovery document, set `client_signing_alg` explicitly.
43
+
44
+ ## [1.0.1] - 2026-03-23
45
+
46
+ - Update jwt dependency
47
+
48
+ ## [1.0.0] - 2026-03-02
49
+
50
+ ### BREAKING CHANGES
51
+ - **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.
52
+ - **Internal Object Types Changed**: Response objects are now custom classes instead of OpenIDConnect library types:
53
+ - `OpenIDConnect::Client` replaced by `OmniauthOidc::Client`
54
+ - `OpenIDConnect::ResponseObject::IdToken` replaced by `OmniauthOidc::ResponseObjects::IdToken`
55
+ - `OpenIDConnect::ResponseObject::UserInfo` replaced by `OmniauthOidc::ResponseObjects::UserInfo`
56
+ - `Rack::OAuth2::AccessToken` replaced by `OmniauthOidc::ResponseObjects::AccessToken`
57
+ - **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.
58
+ - **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.
59
+ - **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).
60
+ - **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`.
61
+ - **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.
62
+
63
+ ### Added
64
+ - **Custom HTTP Client** (`OmniauthOidc::HttpClient`): Net::HTTP-based client for all HTTP requests, removing external HTTP client dependencies entirely
65
+ - GET requests follow up to 5 redirects (301, 302, 307, 308), including relative redirects
66
+ - POST requests reject redirects to prevent credential leakage
67
+ - **Custom OIDC Client** (`OmniauthOidc::Client`): Handles authorization URI construction, token exchange, and userinfo fetching
68
+ - **Response Objects** (`OmniauthOidc::ResponseObjects`): `IdToken`, `UserInfo`, and `AccessToken` classes with method-style access to standard OIDC claims
69
+ - **Configuration Fetcher** (`OmniauthOidc::ConfigFetcher`): Fetches and parses `.well-known/openid-configuration` with retry support
70
+ - **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)
71
+ - **JWKS Caching** (`OmniauthOidc::JwksCache`): Thread-safe JWKS cache with configurable TTL (default 1 hour)
72
+ - Automatic cache invalidation and retry on signature verification failure
73
+ - Manual cache control via `OmniauthOidc::JwksCache.clear!` and `.invalidate(uri)`
74
+ - Configurable via `jwks_cache_ttl` option
75
+ - **Logging & Instrumentation** (`OmniauthOidc::Logging`): Logging via Ruby Logger with optional ActiveSupport::Notifications integration
76
+ - Configurable log levels (default: WARN)
77
+ - Automatic sanitization of sensitive data (tokens, secrets, code verifiers)
78
+ - Event instrumentation for config fetch, token exchange, userinfo fetch, JWKS fetch, request phase, and callback phase
79
+ - **Error Hierarchy**: Specific error classes for all failure modes
80
+ - `TokenVerificationError`, `TokenExpiredError`, `InvalidAlgorithmError`, `InvalidSignatureError`
81
+ - `InvalidIssuerError`, `InvalidAudienceError`, `InvalidNonceError`
82
+ - `JwksFetchError`, `KeyNotFoundError`
83
+ - `ConfigurationError`, `MissingConfigurationError`
84
+ - **Configuration Validation**: Required options (`identifier`, `secret`, `config_endpoint`) are validated on first request with a clear error message listing all missing fields
85
+ - **RBS Type Signatures** (`sig/omniauth_oidc.rbs`): Full type declarations for all public API classes
86
+ - **Comprehensive Test Suite**: Unit tests for HTTP client, JWK handler, JWKS cache, logging, errors, and strategy configuration
87
+
88
+ ### Fixed
89
+ - **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.
90
+ - **Dead Code Removed**: Removed `decode` method in Verify module that referenced undefined `UrlSafeBase64` constant
91
+ - **Typo**: Fixed `client_singing_alg` to `client_signing_alg` in error messages
92
+ - **Scope Default**: Fixed default scope fallback from `[:open_id]` (typo) to `[:openid]`
93
+ - **AuthHash Consistency**: Consolidated duplicate user info fetching and AuthHash construction into OmniAuth DSL blocks
94
+ - **Removed `resolve_endpoint_from_host`**: Endpoints are now used as full URLs from the discovery document instead of being stripped to relative paths
95
+
96
+ ### Changed
97
+ - **Module Loading**: Replaced `Dir.glob` with explicit `require_relative` for clarity and predictable load order
98
+ - **Dependency Constraints**: Runtime dependencies reduced to `omniauth ~> 2.1` and `jwt ~> 2.7`
99
+ - **CI Updates**: Added Ruby 4.0.1 to test matrix, updated `actions/checkout` to v6, RuboCop runs on Ruby 3.3
100
+ - **RuboCop Config**: Fixed invalid cop name `Metrics/Metrics/CyclomaticComplexity`, added `NewCops: enable`
101
+
102
+ ### Migration Guide from 0.x to 1.0.0
103
+
104
+ 1. **Dependencies**: Remove gems that were only used by this gem, then run `bundle install`:
105
+ - `httparty`
106
+ - `openid_connect`
107
+ - `openid_config_parser`
108
+ - `json-jwt`
109
+ 2. **Session Keys**: If you manually access session keys, update to the new namespaced format: `omniauth.{provider_name}.state`, `omniauth.{provider_name}.nonce`.
110
+ 3. **Scope Handling**: If your code treats `scope` as an Array, update it. `scope` now returns a space-delimited String.
111
+ 4. **Error Handling**: Update rescue clauses to catch the new error classes if needed. For example:
112
+ - `Rack::OAuth2::Client::Error` -> `OmniauthOidc::TokenError`
113
+ - Algorithm mismatches now raise `OmniauthOidc::InvalidAlgorithmError` instead of `CallbackError`
114
+ 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.
115
+ 6. **Logging** (optional): Configure logging level: `OmniauthOidc::Logging.log_level = Logger::INFO`
116
+ 7. **Ruby 4.0+**: Add `gem "ostruct"` to your Gemfile (removed from default gems in Ruby 4.0).
117
+
3
118
  ## [0.2.7] - 2024-10-11
4
119
  - Dependencies update
5
120
 
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,32 +67,34 @@ 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.
97
+ Ensure to replace identifier, secret, configuration endpoint URL and others with credentials received from your OIDC provider.
94
98
  Please note that the gem does not accept `redirect_uri` as a configurable option. For details please see section Routes.
95
99
 
96
100
  ### Redirecting for Authentication
@@ -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,48 @@ 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
164
  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`,
165
+ non-configurable value that 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
 
135
170
  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
171
+ token verification. While you can define and use same routes within your Rails app, it is highly recommended to modify
172
+ your `routes.rb` to perform a dynamic redirect to another controller method so this does not cause any conflicts with
138
173
  the middleware or the authorization flow.
139
174
 
140
175
  In an example below, `auth/:provider/callback` is generalized `redirect_uri` value that is passed in the authorization
@@ -163,11 +198,11 @@ end
163
198
  ```
164
199
 
165
200
  **Please note that you should register `https://your_app.com/auth/<simple_provider>/callback` with your OIDC provider
166
- as a callback redirect url.**
201
+ as a callback redirect URL.**
167
202
 
168
203
  ### Using Access Token Without User Info
169
204
 
170
- In case your app requries only an access token and not the user information, then you can specify an optional
205
+ In case your app requires only an access token and not the user information, then you can specify an optional
171
206
  configuration in the omniauth initializer:
172
207
 
173
208
  ```ruby
@@ -185,38 +220,17 @@ Rails.application.config.middleware.use OmniAuth::Builder do
185
220
  end
186
221
  ```
187
222
 
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
- ```
223
+ 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
224
 
211
225
  ### Ending Session
212
226
 
213
227
  The gem provides two configuration options to allow ending a session simultaneously with your client application and the
214
228
  OIDC provider.
215
229
 
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:
230
+ To use this feature, you need to provide a `logout_path` in the options and an `end_session_endpoint` in the client
231
+ options. Here's a sample setup:
218
232
 
219
- ``` ruby
233
+ ```ruby
220
234
  provider :oidc, {
221
235
  name: :simple_provider,
222
236
  client_options: {
@@ -236,42 +250,116 @@ options. Here’s a sample setup:
236
250
  Using these two configurations, you can ensure that when a user logs out from your application, they are also logged out
237
251
  from the OIDC provider, providing a seamless logout across multiple services.
238
252
 
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
253
+ This works by calling `other_phase` on every controller request in your application. The method checks if the requested
254
+ URL matches the defined `logout_path`. If it does (i.e. current user has requested to log out from your application)
255
+ `other_phase` performs a redirect to the `end_session_endpoint` to terminate the user's session with the OIDC provider
242
256
  and then it returns back to your application and concludes the request to end the current user's session.
243
257
 
244
258
  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
259
 
260
+ ### Logging
261
+
262
+ The gem includes built-in logging with automatic sensitive data sanitization. By default, log level is set to WARN.
263
+
264
+ ```ruby
265
+ # Set log level
266
+ OmniauthOidc::Logging.log_level = Logger::INFO
267
+
268
+ # Use a custom logger
269
+ OmniauthOidc::Logging.logger = Rails.logger
270
+ ```
271
+
272
+ If ActiveSupport::Notifications is available (e.g. in Rails), the gem publishes instrumentation events:
273
+
274
+ - `config.fetch.omniauth_oidc`: OIDC discovery document fetch
275
+ - `token.exchange.omniauth_oidc`: authorization code to token exchange
276
+ - `userinfo.fetch.omniauth_oidc`: userinfo endpoint call
277
+ - `jwks.fetch.omniauth_oidc`: JWKS fetch
278
+ - `request_phase.start.omniauth_oidc`: authorization redirect
279
+ - `callback_phase.start.omniauth_oidc`: callback processing
280
+ - `id_token.verify.omniauth_oidc`: ID token verification
281
+
282
+ ### Error Handling
283
+
284
+ The gem raises specific error classes that you can rescue in your callback handling:
285
+
286
+ | Error Class | When Raised |
287
+ |---|---|
288
+ | `OmniauthOidc::MissingConfigurationError` | Required options (`identifier`, `secret`, `config_endpoint`) are missing |
289
+ | `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) |
290
+ | `OmniauthOidc::TokenError` | Token exchange fails, or PKCE is enabled and no code verifier is stored in the session |
291
+ | `OmniauthOidc::TokenVerificationError` | JWT format is invalid, the ID token has no numeric `exp` claim, or no subject (`sub`) could be determined |
292
+ | `OmniauthOidc::TokenExpiredError` | ID token `exp` claim is in the past, beyond `clock_skew_leeway` |
293
+ | `OmniauthOidc::InvalidAlgorithmError` | JWT algorithm is not accepted (see [Security Defaults](#security-defaults)) |
294
+ | `OmniauthOidc::InvalidSignatureError` | JWT signature verification fails |
295
+ | `OmniauthOidc::InvalidIssuerError` | ID token `iss` does not match expected issuer |
296
+ | `OmniauthOidc::InvalidAudienceError` | ID token `aud` does not match client identifier |
297
+ | `OmniauthOidc::InvalidNonceError` | ID token `nonce` does not match the stored nonce, or no nonce is stored when one is required |
298
+ | `OmniauthOidc::JwksFetchError` | JWKS endpoint fetch fails |
299
+
300
+ All error classes inherit from `OmniauthOidc::Error < RuntimeError`.
301
+
302
+ During the request and callback phases these errors do not propagate as exceptions. They are passed to OmniAuth's
303
+ failure handler, which by default redirects to `/auth/failure?message=<key>` with one of these keys: `csrf_detected`,
304
+ `missing_code`, `missing_id_token`, `token_error`, `http_error`, `timeout`, `failed_to_connect`, `configuration_error`
305
+ or `jwks_error`. The exception itself is available in `request.env['omniauth.error']`.
306
+
307
+ ### Security Defaults
308
+
309
+ 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):
310
+
311
+ - **Signature and algorithm**: the accepted algorithms come from configuration, never from the token header. They are
312
+ `client_signing_alg` when set, otherwise the provider's `id_token_signing_alg_values_supported`, otherwise `RS256`.
313
+ Unsigned (`alg: none`) tokens are always rejected, and an empty HMAC secret is refused.
314
+ - **Claims**: `iss` must equal the discovery `issuer`, `aud` must contain the client `identifier`, `exp` is required,
315
+ and `exp`/`nbf` allow `clock_skew_leeway` seconds of drift.
316
+ - **Nonce**: generated per login and stored in the session. It is required when `send_nonce` is on (the default) and
317
+ always for `response_type: 'id_token'`. It is never read from request parameters.
318
+ - **PKCE**: on by default. The code verifier is read only from the session.
319
+ - **UserInfo**: the response is used only when its `sub` matches the ID token `sub` (OIDC Core 5.3.4).
320
+ - **HTTP**: requests time out after 5s (connect) and 10s (read). Redirects never downgrade from HTTPS to HTTP, and the
321
+ `Authorization` header is dropped when a redirect leaves the original host.
322
+ - **Caching**: the discovery document and JWKS are cached per process. An ID token with an unknown `kid` triggers at
323
+ most one JWKS refresh per minute, so signing key rotation is picked up without letting forged tokens flood the
324
+ provider.
325
+
246
326
  ### Advanced Configuration
327
+
247
328
  You can customize the OIDC strategy further by adding additional configuration options:
248
329
 
249
330
  | Field | Description | Required | Default Value | Example/Notes |
250
331
  |------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|-------------------------------------|-------------------------------------------------------|
251
332
  | 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]` |
333
+ | issuer | Root url for the OIDC authorization server | no | retrieved from config_endpoint | `"https://simpleprovider.com"` |
334
+ | 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` |
335
+ | client_signing_alg | Expected JWT signing algorithm. Tokens signed with any other algorithm are rejected | no | `nil` (provider-advertised, else RS256) | `"RS256"`, `"HS256"` |
336
+ | 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
337
  | response_type | OAuth2 response type expected from OIDC provider during authorization | no | `"code"` | `"code"` or `"id_token"` |
257
338
  | 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
339
  | require_state | Boolean to indicate if state param should be verified. This is a recommendation by OIDC spec | no | `true` | `true` or `false` |
259
340
  | 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
341
  | 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
342
  | prompt | Specifies whether the OIDC authorization server prompts the end user for reauthentication and consent | no | `nil` | `:none`, `:login`, `:consent` or `:select_account` |
343
+ | 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
344
  | send_scope_to_token_endpoint | Should the scope parameter be sent to the authorization token endpoint | no | `true` | `true` or `false` |
263
345
  | 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"` |
346
+ | 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
347
  | extra_authorize_params | Hash of extra fixed parameters that will be merged to the authorization request | no | `{}` | `{"tenant" => "common"}` |
266
348
  | 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` |
349
+ | pkce | Enable [PKCE flow](https://oauth.net/2/pkce/) | no | `true` | `true` or `false` |
268
350
  | 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 |
351
+ | 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
352
  | client_options | Hash of client options detailed below in a separate table | yes | see below | see below |
271
353
  | 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
-
354
+ | 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"}'` |
355
+ | client_x509_signing_key | X.509 certificate (PEM format) for local signature verification | no | `nil` | PEM string |
356
+ | logout_path | Log out is only triggered when the request path ends on this path | no | `"/logout"` | `"/sign_out"` |
357
+ | jwks_cache_ttl | JWKS cache time-to-live in seconds, shared by all requests in the process | no | `3600` (1 hour) | `7200` |
358
+ | 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 |
359
+ | clock_skew_leeway | Seconds of clock drift allowed when checking the ID token `exp` and `nbf` claims | no | `60` | `0` to disable |
360
+ | hd | Google-specific: hosted domain parameter | no | `nil` | `"example.com"` |
361
+ | max_age | Maximum authentication age in seconds | no | `nil` | `3600` |
362
+ | acr_values | Authentication Class Reference (ACR) values per [RFC9470](https://www.rfc-editor.org/rfc/rfc9470.html) | no | `nil` | `"c1 c2"` |
275
363
 
276
364
  Below are options for the `client_options` hash of the configuration:
277
365
 
@@ -280,14 +368,14 @@ Below are options for the `client_options` hash of the configuration:
280
368
  | identifier | OAuth2 client_id | yes | `nil` |
281
369
  | secret | OAuth2 client secret | yes | `nil` |
282
370
  | 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` |
371
+ | scheme | HTTP scheme to use | no | `"https"` |
372
+ | host | Host of the authorization server | no | `nil` |
373
+ | port | Port for the authorization server | no | `443` |
374
+ | authorization_endpoint | Authorize endpoint on the authorization server | no | retrieved from config_endpoint |
375
+ | token_endpoint | Token endpoint on the authorization server | no | retrieved from config_endpoint |
376
+ | userinfo_endpoint | User info endpoint on the authorization server | no | retrieved from config_endpoint |
377
+ | jwks_uri | JWKS URI on the authorization server | no | retrieved from config_endpoint |
378
+ | end_session_endpoint | URL to call to log the user out at the authorization server | no | `nil` |
291
379
 
292
380
  ## Contributing
293
381