omniauth-oidc-strategy 0.3.2

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2c3a01044e3cdcdfd2a0712deb95c1f8d015c11dd0af41cb9f46d647e8add7d9
4
+ data.tar.gz: 682e13153d0afe1e9ba025417b665a33bf7f67b0ebbeb1e36a5fef27c299cdc1
5
+ SHA512:
6
+ metadata.gz: b049f61a08d5f64802a3e486aff0ccbed8c78a3632501f71145867d63910ac7a0c1ba50cf94270e809005e7963b7a8fd444fe25b22beb0a0f27c7f3dfed9bd96
7
+ data.tar.gz: bc093f7a404270346fc0ceab91471d6d80f9d4a6ca20de69c0877ffe751b85b28b2e87516a426b7f74d52690ac946dc8b48a07acc90934d9e6d2812e19828083
data/.rubocop.yml ADDED
@@ -0,0 +1,5 @@
1
+ # Omakase Ruby styling for Rails
2
+ inherit_gem:
3
+ rubocop-rails-omakase: rubocop.yml
4
+
5
+ # Your own specialized rules go here
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ ## [Released]
2
+
3
+ ## [0.2.3] - 2024-08-04
4
+ - Update readme
5
+
6
+ ## [0.2.2] - 2024-08-04
7
+ - Update dependencies, update documentation, fix end_session_uri, update other_phase
8
+
9
+ ## [0.2.1] - 2024-07-21
10
+ - Update dependencies
11
+
12
+ ## [0.2.0] - 2024-07-06
13
+ - Add option to fetch user info or skip it
14
+
15
+ ## [0.1.1] - 2024-06-16
16
+ - Add dependabot
17
+
18
+ ## [0.1.0] - 2024-06-13
19
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at slmusayev@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Suleyman Musayev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,235 @@
1
+ # OmniAuth::Oidc
2
+
3
+ [![CI](https://github.com/CanalWestStudio/omniauth-oidc/actions/workflows/pull_request.yml/badge.svg)](https://github.com/CanalWestStudio/omniauth-oidc/actions/workflows/pull_request.yml)
4
+ [![Gem Version](https://badge.fury.io/rb/omniauth-oidc.svg)](https://badge.fury.io/rb/omniauth-oidc)
5
+
6
+ An OmniAuth strategy for OpenID Connect (OIDC) authentication. Supports multiple OIDC providers, PKCE, RP-Initiated Logout, and automatic discovery via the provider's configuration endpoint.
7
+
8
+ Requires Ruby 3.1+.
9
+
10
+ ## Installation
11
+
12
+ $ bundle add omniauth-oidc
13
+
14
+ Or install directly:
15
+
16
+ $ gem install omniauth-oidc
17
+
18
+ ## Configuration
19
+
20
+ You need a Client ID, Client Secret, and the OIDC configuration endpoint URL at minimum.
21
+
22
+ ```ruby
23
+ # config/initializers/omniauth.rb
24
+ Rails.application.config.middleware.use OmniAuth::Builder do
25
+ provider :oidc, {
26
+ name: :my_provider,
27
+ client_options: {
28
+ identifier: ENV["MY_PROVIDER_CLIENT_ID"],
29
+ secret: ENV["MY_PROVIDER_CLIENT_SECRET"],
30
+ config_endpoint: "https://provider.example.com/.well-known/openid-configuration"
31
+ }
32
+ }
33
+ end
34
+ ```
35
+
36
+ With Devise:
37
+
38
+ ```ruby
39
+ Devise.setup do |config|
40
+ config.omniauth :oidc, {
41
+ name: :my_provider,
42
+ scope: [:openid, :email, :profile],
43
+ uid_field: "preferred_username",
44
+ client_options: {
45
+ identifier: ENV["MY_PROVIDER_CLIENT_ID"],
46
+ secret: ENV["MY_PROVIDER_CLIENT_SECRET"],
47
+ config_endpoint: "https://provider.example.com/.well-known/openid-configuration"
48
+ }
49
+ }
50
+ end
51
+ ```
52
+
53
+ The gem fetches authorization, token, userinfo, and JWKS endpoints automatically from the `config_endpoint`. You can override any of them explicitly in `client_options` if needed.
54
+
55
+ The gem does not accept `redirect_uri` as a configurable option — it is built dynamically from the provider `name` (see [Routes](#routes)).
56
+
57
+ ### All Options
58
+
59
+ | Option | Description | Default |
60
+ |---|---|---|
61
+ | `name` | Provider identifier, used in route paths | `:oidc` |
62
+ | `issuer` | Expected token issuer | Fetched from `config_endpoint` |
63
+ | `scope` | OIDC scopes | `[:openid]` |
64
+ | `response_type` | `"code"` or `"id_token"` | `"code"` |
65
+ | `response_mode` | `:query`, `:fragment`, `:form_post`, or `:web_message` | `nil` |
66
+ | `display` | `:page`, `:popup`, `:touch`, or `:wap` | `nil` |
67
+ | `prompt` | `:none`, `:login`, `:consent`, or `:select_account` | `nil` |
68
+ | `require_state` | Verify the `state` parameter on callbacks | `true` |
69
+ | `state` | Custom state value or a `Proc` that returns one | Random 16-byte hex |
70
+ | `send_nonce` | Include a nonce in the authorization request | `true` |
71
+ | `fetch_user_info` | Fetch user info from the userinfo endpoint | `true` |
72
+ | `uid_field` | User info field to use as `uid` | `"sub"` |
73
+ | `send_scope_to_token_endpoint` | Include scope in the token request | `true` |
74
+ | `client_auth_method` | Auth method for the token endpoint (e.g. `:basic`, `:jwks`) | `:basic` |
75
+ | `pkce` | Enable PKCE (S256) | `false` |
76
+ | `pkce_verifier` | Custom PKCE verifier `Proc` | Random 128-char hex |
77
+ | `pkce_options` | Custom code challenge generation `Proc` and method | SHA256 / `"S256"` |
78
+ | `extra_authorize_params` | Hash of extra params merged into the authorization request | `{}` |
79
+ | `allow_authorize_params` | List of dynamic param keys allowed from the request | `[]` |
80
+ | `acr_values` | Authentication Class Reference values ([RFC 9470](https://www.rfc-editor.org/rfc/rfc9470.html)) | `nil` |
81
+ | `logout_path` | Path that triggers RP-Initiated Logout | `"/logout"` |
82
+ | `post_logout_redirect_uri` | Where to redirect after provider logout | `nil` |
83
+ | `client_signing_alg` | Expected JWT signing algorithm (e.g. `:RS256`) | `nil` (any) |
84
+ | `jwt_secret_base64` | Base64-encoded secret for HMAC signing algorithms | `client_options.secret` |
85
+ | `client_jwk_signing_key` | JWK key for JWT verification | `nil` |
86
+ | `client_x509_signing_key` | X.509 certificate for JWT verification | `nil` |
87
+
88
+ ### Client Options
89
+
90
+ | Option | Description | Default |
91
+ |---|---|---|
92
+ | `identifier` | OAuth 2.0 client ID | **required** |
93
+ | `secret` | OAuth 2.0 client secret | **required** |
94
+ | `config_endpoint` | OIDC discovery endpoint URL | **required** |
95
+ | `scheme` | HTTP scheme | `"https"` |
96
+ | `host` | Authorization server host | From `config_endpoint` |
97
+ | `port` | Authorization server port | `443` |
98
+ | `authorization_endpoint` | Override discovered authorize URL | From `config_endpoint` |
99
+ | `token_endpoint` | Override discovered token URL | From `config_endpoint` |
100
+ | `userinfo_endpoint` | Override discovered userinfo URL | From `config_endpoint` |
101
+ | `jwks_uri` | Override discovered JWKS URL | From `config_endpoint` |
102
+ | `end_session_endpoint` | Provider logout URL | From `config_endpoint` |
103
+ | `environment` | Custom environment param sent with authorization requests | `nil` |
104
+
105
+ ## Routes
106
+
107
+ The callback URL follows the pattern `https://your-app.com/auth/<name>/callback`, where `<name>` is the provider name from your configuration. Register this URL with your OIDC provider as an allowed redirect URI.
108
+
109
+ ```ruby
110
+ # config/routes.rb
111
+ Rails.application.routes.draw do
112
+ match "auth/:provider/callback", to: "callbacks#omniauth", via: [:get, :post]
113
+ end
114
+ ```
115
+
116
+ To initiate authentication, use a POST link (OmniAuth requires POST for CSRF protection):
117
+
118
+ ```ruby
119
+ <%= button_to "Login with My Provider", "/auth/my_provider" %>
120
+ ```
121
+
122
+ ## Handling Callbacks
123
+
124
+ ```ruby
125
+ class CallbacksController < ApplicationController
126
+ def omniauth
127
+ auth = request.env["omniauth.auth"]
128
+
129
+ user = User.find_or_create_by(uid: auth["uid"]) do |u|
130
+ u.name = auth["info"]["name"]
131
+ u.email = auth["info"]["email"]
132
+ end
133
+
134
+ session[:user_id] = user.id
135
+ redirect_to root_path, notice: "Logged in"
136
+ end
137
+ end
138
+ ```
139
+
140
+ ### Access Token Only (No User Info)
141
+
142
+ Set `fetch_user_info: false` to skip the userinfo endpoint. The callback will contain only credentials:
143
+
144
+ ```ruby
145
+ provider :oidc, {
146
+ name: :my_provider,
147
+ fetch_user_info: false,
148
+ client_options: {
149
+ identifier: ENV["MY_PROVIDER_CLIENT_ID"],
150
+ secret: ENV["MY_PROVIDER_CLIENT_SECRET"],
151
+ config_endpoint: "https://provider.example.com/.well-known/openid-configuration"
152
+ }
153
+ }
154
+ ```
155
+
156
+ ```ruby
157
+ # request.env["omniauth.auth"] will contain:
158
+ # {
159
+ # "provider" => :my_provider,
160
+ # "credentials" => {
161
+ # "id_token" => "...",
162
+ # "token" => "...",
163
+ # "refresh_token" => "...",
164
+ # "expires_in" => 300,
165
+ # "scope" => nil
166
+ # }
167
+ # }
168
+ ```
169
+
170
+ ## RP-Initiated Logout
171
+
172
+ To log the user out of both your application and the OIDC provider, configure `logout_path` and `end_session_endpoint`:
173
+
174
+ ```ruby
175
+ provider :oidc, {
176
+ name: :my_provider,
177
+ logout_path: "/logout",
178
+ post_logout_redirect_uri: "https://your-app.com/signed_out",
179
+ client_options: {
180
+ identifier: ENV["MY_PROVIDER_CLIENT_ID"],
181
+ secret: ENV["MY_PROVIDER_CLIENT_SECRET"],
182
+ config_endpoint: "https://provider.example.com/.well-known/openid-configuration",
183
+ end_session_endpoint: "https://provider.example.com/signout"
184
+ }
185
+ }
186
+ ```
187
+
188
+ When a request matches `logout_path`, the gem redirects to the provider's `end_session_endpoint` with `id_token_hint` (from the session) and `post_logout_redirect_uri` if configured.
189
+
190
+ The `end_session_endpoint` can also be discovered automatically from the `config_endpoint` if the provider advertises it.
191
+
192
+ See the [OIDC RP-Initiated Logout spec](https://openid.net/specs/openid-connect-rpinitiated-1_0.html) for details.
193
+
194
+ ## Security
195
+
196
+ ### What the gem handles
197
+
198
+ - **TLS 1.2+** — All HTTP requests enforce a minimum of TLS 1.2, allowing TLS 1.3 negotiation
199
+ - **State validation** — The `state` parameter is verified on callbacks to prevent CSRF (enabled by default)
200
+ - **Nonce verification** — A session-stored nonce is used for ID token verification; nonces from request params are never accepted
201
+ - **PKCE** — Proof Key for Code Exchange (S256) is available via `pkce: true`
202
+ - **Security headers** — All redirects include `Cache-Control: no-cache, no-store`, `Pragma: no-cache`, and `Referrer-Policy: no-referrer`
203
+ - **RP-Initiated Logout** — Sends `id_token_hint` with end-session requests per the OIDC spec
204
+ - **No `open-uri`** — The gem avoids `Kernel.open` by using Faraday for all HTTP
205
+
206
+ ### Host application responsibilities
207
+
208
+ **Session and cookie security:**
209
+ - Configure session cookies with `Secure`, `HttpOnly`, and `SameSite=Lax` (or `Strict`)
210
+ - In Rails: `config.session_store :cookie_store, secure: true, httponly: true, same_site: :lax`
211
+
212
+ **HTTPS:**
213
+ - Enforce HTTPS on all pages
214
+ - In Rails: `config.force_ssl = true`
215
+
216
+ **Token storage:**
217
+ - Encrypt refresh tokens at rest if persisted (e.g. AES-256-GCM)
218
+ - Store encryption keys separately from encrypted data
219
+ - Never log OAuth tokens or user credentials
220
+
221
+ **Input handling:**
222
+ - Sanitize user info from the OIDC provider before rendering in views
223
+ - Use parameterized queries when storing user data
224
+
225
+ ### Reporting vulnerabilities
226
+
227
+ If you discover a security vulnerability, please report it privately via [GitHub Security Advisories](https://github.com/CanalWestStudio/omniauth-oidc/security/advisories) rather than opening a public issue.
228
+
229
+ ## Contributing
230
+
231
+ Bug reports and pull requests are welcome on GitHub at https://github.com/CanalWestStudio/omniauth-oidc. Contributors are expected to adhere to the [code of conduct](https://github.com/CanalWestStudio/omniauth-oidc/blob/main/CODE_OF_CONDUCT.md).
232
+
233
+ ## License
234
+
235
+ Available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniauthOidc
4
+ # Fetches and wraps the OIDC provider's discovery document, providing
5
+ # method-based access to standard OpenID Connect configuration fields.
6
+ class Config
7
+ FIELDS = %i[
8
+ issuer
9
+ authorization_endpoint
10
+ token_endpoint
11
+ userinfo_endpoint
12
+ jwks_uri
13
+ end_session_endpoint
14
+ scopes_supported
15
+ ].freeze
16
+
17
+ attr_reader(*FIELDS)
18
+
19
+ def initialize(data)
20
+ FIELDS.each do |field|
21
+ instance_variable_set(:"@#{field}", data[field.to_s] || data[field])
22
+ end
23
+ end
24
+
25
+ DEFAULT_TTL = 3600 # 1 hour
26
+
27
+ def self.fetch(endpoint_url, ttl: DEFAULT_TTL)
28
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
29
+
30
+ if (cached = cache[endpoint_url]) && (now - cached[:fetched_at] < ttl)
31
+ return cached[:config]
32
+ end
33
+
34
+ json = OmniAuth::Strategies::Oidc::Transport.fetch_json(endpoint_url)
35
+ config = new(json)
36
+ cache[endpoint_url] = { config: config, fetched_at: now }
37
+ config
38
+ end
39
+
40
+ def self.cache
41
+ @cache ||= {}
42
+ end
43
+
44
+ def self.clear_cache!
45
+ @cache = {}
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniauthOidc
4
+ class Error < RuntimeError; end
5
+
6
+ class MissingCodeError < Error; end
7
+
8
+ class MissingIdTokenError < Error; end
9
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "./version"
4
+
5
+ module OmniauthOidc
6
+ USER_AGENT = "#{name}Client #{VERSION}-#{RUBY_PLATFORM}"
7
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniauthOidc
4
+ VERSION = "0.3.2"
5
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniAuth
4
+ module Strategies
5
+ class Oidc
6
+ # Callback phase
7
+ module Callback
8
+ def callback_phase # rubocop:disable Metrics
9
+ error_handler
10
+
11
+ verify_id_token!(params["id_token"]) if configured_response_type == "id_token"
12
+
13
+ client.redirect_uri = redirect_uri
14
+
15
+ return id_token_callback_phase if configured_response_type == "id_token"
16
+
17
+ client.authorization_code = authorization_code
18
+
19
+ access_token
20
+ super
21
+ rescue CallbackError => e
22
+ fail!(e.error, e)
23
+ rescue ::Rack::OAuth2::Client::Error => e
24
+ fail!(e.response[:error], e)
25
+ rescue ::Timeout::Error, ::Errno::ETIMEDOUT => e
26
+ fail!(:timeout, e)
27
+ rescue ::SocketError => e
28
+ fail!(:failed_to_connect, e)
29
+ end
30
+
31
+ private
32
+
33
+ def access_token
34
+ return @access_token if @access_token
35
+
36
+ token_request_params = {
37
+ scope: (scope if options.send_scope_to_token_endpoint),
38
+ client_auth_method: options.client_auth_method
39
+ }
40
+
41
+ if options.pkce
42
+ token_request_params[:code_verifier] =
43
+ params["code_verifier"] || session.delete("omniauth.pkce.verifier")
44
+ end
45
+
46
+ set_client_options_for_callback_phase
47
+
48
+ @access_token = client.access_token!(token_request_params)
49
+
50
+ if configured_response_type == "code"
51
+ verify_id_token!(@access_token.id_token)
52
+ store_id_token(@access_token.id_token)
53
+ end
54
+
55
+ options.fetch_user_info ? get_user_info_from_access_token : define_access_token
56
+ end
57
+
58
+ def id_token_callback_phase
59
+ decode_id_token(params["id_token"])
60
+ store_id_token(params["id_token"])
61
+
62
+ define_user_info
63
+ end
64
+
65
+ def valid_response_type?
66
+ return true if params.key?(configured_response_type)
67
+
68
+ error_attrs = RESPONSE_TYPE_EXCEPTIONS[configured_response_type]
69
+ fail!(error_attrs[:key], error_attrs[:exception_class].new(params["error"]))
70
+
71
+ false
72
+ end
73
+
74
+ def get_user_info_from_access_token
75
+ define_user_info
76
+ end
77
+
78
+ def define_user_info
79
+ env["omniauth.auth"] = AuthHash.new(serialized_user_info_auth_hash)
80
+ end
81
+
82
+ def define_access_token
83
+ env["omniauth.auth"] = AuthHash.new(serialized_access_token_auth_hash)
84
+ end
85
+
86
+ def store_id_token(id_token)
87
+ session["omniauth.id_token"] = id_token if id_token
88
+ end
89
+
90
+ def configured_response_type
91
+ @configured_response_type ||= options.response_type.to_s
92
+ end
93
+
94
+ def set_client_options_for_callback_phase
95
+ configure_discovery_endpoints(client)
96
+ client.redirect_uri = redirect_uri
97
+ end
98
+
99
+ def error_handler
100
+ error = params["error_reason"] || params["error"]
101
+ error_description = params["error_description"] || params["error_reason"]
102
+
103
+ raise CallbackError, error: params["error"], reason: error_description, uri: params["error_uri"] if error
104
+
105
+ verify_state!
106
+
107
+ return unless valid_response_type?
108
+
109
+ options.issuer = issuer if options.issuer.nil? || options.issuer.empty?
110
+ end
111
+
112
+ def verify_state!
113
+ session_state = stored_state
114
+
115
+ if options.require_state
116
+ if params["state"].to_s.empty? || params["state"] != session_state
117
+ raise CallbackError, error: :csrf_detected, reason: "Invalid 'state' parameter"
118
+ end
119
+ elsif !params["state"].to_s.empty? && params["state"] != session_state
120
+ raise CallbackError, error: :csrf_detected, reason: "Invalid 'state' parameter"
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniAuth
4
+ module Strategies
5
+ class Oidc
6
+ # Code request phase
7
+ module Request
8
+ def request_phase
9
+ @identifier = client_options.identifier
10
+ @secret = secret
11
+
12
+ set_client_options_for_request_phase
13
+ redirect authorize_uri
14
+ end
15
+
16
+ def authorize_uri # rubocop:disable Metrics/AbcSize
17
+ client.redirect_uri = redirect_uri
18
+ opts = serialized_request_options
19
+
20
+ opts.merge!(options.extra_authorize_params) unless options.extra_authorize_params.empty?
21
+
22
+ options.allow_authorize_params.each do |key|
23
+ opts[key] = request.params[key.to_s] unless opts.key?(key)
24
+ end
25
+
26
+ # Add environment to the request if it is set
27
+ opts[:environment] = client_options.environment if client_options.environment
28
+
29
+ if options.pkce
30
+ verifier = options.pkce_verifier ? options.pkce_verifier.call : SecureRandom.hex(64)
31
+
32
+ opts.merge!(pkce_authorize_params(verifier))
33
+ session["omniauth.pkce.verifier"] = verifier
34
+ end
35
+
36
+ client.authorization_uri(opts.reject { |_k, v| v.nil? })
37
+ end
38
+
39
+ private
40
+
41
+ def new_state
42
+ state = if options.state.respond_to?(:call)
43
+ if options.state.arity == 1
44
+ options.state.call(env)
45
+ else
46
+ options.state.call
47
+ end
48
+ end
49
+ session["omniauth.state"] = state || SecureRandom.hex(16)
50
+ end
51
+
52
+ def set_client_options_for_request_phase
53
+ configure_discovery_endpoints(client_options)
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end