any_auth 0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 64e8f1d4f67339c3ac209d8b86f0a184381b42a5eb672ba1b31919c791247c12
4
+ data.tar.gz: 3497cbd74e6a5b41c506a76a2bdad2da90b11a852067b3b5309a26170ffa4097
5
+ SHA512:
6
+ metadata.gz: 659eed9f561175a3f05151b7a27bfc00f436fbfd6420a8fb81de5be16c5181dfa9f9e1f21e19ea9b08c684d3416a5c393b1ead0ff0b9e059530ecafc480fbf34
7
+ data.tar.gz: 7b149adb51811d7c2303954db76db827ea8d303b8d9c7cdff5899a34755e8b73de3c678346a3d058ea1ce1d4a9d20af2fbab49e996e52bab5a7de22897a5fe77
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ The first release: strategies for Google, Microsoft, Apple, SAML, Signicat,
6
+ HubSpot, Shopify, e-conomic, Adversus, Relatel, Tavle and a developer sign-in,
7
+ called from Rails controllers through `AnyAuth::ControllerHelpers`.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Displayful
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,518 @@
1
+ # AnyAuth
2
+
3
+ Sign people in with Google, Microsoft, Apple and others, and connect your app
4
+ to vendors' APIs, from your own Rails controllers. One strategy class per
5
+ vendor, with the request and callback phases OmniAuth names, and no Rack
6
+ middleware.
7
+
8
+ Needs Ruby 3.4 and Rails 8.
9
+
10
+ - [Sign in with Google and Microsoft](#sign-in-with-google-and-microsoft)
11
+ - [Connect to a vendor's API](#connect-to-a-vendors-api)
12
+ - [Reference](#reference)
13
+ - [Writing a strategy](#writing-a-strategy)
14
+ - [Coming from OmniAuth](#coming-from-omniauth)
15
+ - [Testing](#testing)
16
+ - [Developer docs](docs/README.md): adding a strategy, how a sign-in works, each strategy
17
+
18
+ ## Sign in with Google and Microsoft
19
+
20
+ ### 1. Install
21
+
22
+ ```ruby
23
+ # Gemfile
24
+ gem "any_auth"
25
+ ```
26
+
27
+ ### 2. Register the providers
28
+
29
+ Create an OAuth client at each vendor and add your callback address as a
30
+ redirect URI: `https://example.com/auth/google/callback`. Each
31
+ [strategy page](docs/strategies) says where.
32
+
33
+ ```ruby
34
+ # config/initializers/any_auth.rb
35
+ AnyAuth.configure do |config|
36
+ config.provider :google,
37
+ client_id: ENV["GOOGLE_CLIENT_ID"], client_secret: ENV["GOOGLE_CLIENT_SECRET"]
38
+ config.provider :microsoft,
39
+ client_id: ENV["MICROSOFT_CLIENT_ID"], client_secret: ENV["MICROSOFT_CLIENT_SECRET"]
40
+ end
41
+ ```
42
+
43
+ ### 3. Add the routes
44
+
45
+ ```ruby
46
+ # config/routes.rb
47
+ scope "auth/:provider", module: :auth, as: :auth do
48
+ resource :authorization, only: :create
49
+ resource :callback, only: :show
50
+ end
51
+ ```
52
+
53
+ Two resources: `POST /auth/google/authorization` starts the sign-in, and
54
+ `GET /auth/google/callback` is where the vendor sends the person back.
55
+
56
+ ### 4. Write the controllers
57
+
58
+ The examples build on the Rails 8 authentication generator
59
+ (`bin/rails generate authentication`), which gives you `start_new_session_for`
60
+ and `after_authentication_url`.
61
+
62
+ ```ruby
63
+ # app/controllers/auth/base_controller.rb
64
+ class Auth::BaseController < ApplicationController
65
+ include AnyAuth::ControllerHelpers
66
+
67
+ allow_unauthenticated_access
68
+ before_action :set_strategy
69
+ rescue_from AnyAuth::AuthenticationError, with: :refused
70
+
71
+ private
72
+ def set_strategy
73
+ @strategy = AnyAuth.strategy(params[:provider])
74
+ end
75
+
76
+ def refused
77
+ redirect_to new_session_path, alert: "Try another way to sign in."
78
+ end
79
+ end
80
+ ```
81
+
82
+ ```ruby
83
+ # app/controllers/auth/authorizations_controller.rb
84
+ class Auth::AuthorizationsController < Auth::BaseController
85
+ def create
86
+ redirect_to_provider @strategy, redirect_uri: auth_callback_url(params[:provider])
87
+ end
88
+ end
89
+ ```
90
+
91
+ ```ruby
92
+ # app/controllers/auth/callbacks_controller.rb
93
+ class Auth::CallbacksController < Auth::BaseController
94
+ def show
95
+ if user = User.from_any_auth(authenticate_with_provider(@strategy))
96
+ start_new_session_for user
97
+ redirect_to after_authentication_url
98
+ else
99
+ refused
100
+ end
101
+ end
102
+ end
103
+ ```
104
+
105
+ `redirect_to_provider` keeps what the callback needs in a short-lived
106
+ encrypted cookie of its own and sends the person to the vendor. `authenticate_with_provider` checks the callback,
107
+ swaps the code for tokens, asks who signed in and returns an `auth`. A failed
108
+ or refused sign-in raises an `AnyAuth::AuthenticationError`, and the person
109
+ lands back on the sign-in page. A setup mistake the vendor reports, such as a
110
+ wrong client secret, is an `AnyAuth::ConfigurationError`: not caught here, so
111
+ it becomes an error page and reaches your error tracker.
112
+
113
+ `after_authentication_url` already returns people to the page they were
114
+ asked to sign in on: the generator keeps it in the session, and the trip to
115
+ the vendor leaves it there.
116
+
117
+ `auth_callback_url` is built from the request's `Host` header, which anyone
118
+ can forge. Vendors that match redirect URIs exactly refuse a forged one, but
119
+ not all are strict, so tell Rails which hosts are yours; it then refuses any
120
+ other before your controller runs:
121
+
122
+ ```ruby
123
+ # config/environments/production.rb
124
+ config.hosts = %w[ example.com ]
125
+ ```
126
+
127
+ ### 5. Find the person
128
+
129
+ ```ruby
130
+ # app/models/user.rb
131
+ class User < ApplicationRecord
132
+ has_many :sessions, dependent: :destroy
133
+ has_many :identities, dependent: :destroy
134
+
135
+ def self.from_any_auth(auth)
136
+ if identity = Identity.find_by(provider: auth.provider, uid: auth.uid)
137
+ identity.user
138
+ elsif auth.info.email_verified
139
+ find_by(email_address: auth.info.email)&.tap do |user|
140
+ user.identities.create!(provider: auth.provider, uid: auth.uid)
141
+ end
142
+ end
143
+ end
144
+ end
145
+ ```
146
+
147
+ Key a person on `provider` and `uid`, in an `Identity` that belongs to the
148
+ user. Link to an existing account by
149
+ email only when `auth.info.email_verified` is true: AnyAuth sets it only when
150
+ the vendor can vouch for the mailbox, which is stricter than the vendor's own
151
+ flag (see [Google](docs/strategies/google.md) and
152
+ [Microsoft](docs/strategies/microsoft.md)).
153
+
154
+ ### 6. Add the buttons
155
+
156
+ ```erb
157
+ <%= button_to "Sign in with Google", auth_authorization_path(:google), form: { data: { turbo: false } } %>
158
+ <%= button_to "Sign in with Microsoft", auth_authorization_path(:microsoft), form: { data: { turbo: false } } %>
159
+ ```
160
+
161
+ The sign-in starts with a `POST`, and not through Turbo: the browser has to
162
+ follow the redirect to the vendor itself.
163
+
164
+ ### Carrying something through the sign-in
165
+
166
+ Anything passed as `params:` comes back on the `auth`, such as an invitation
167
+ the person was accepting:
168
+
169
+ ```ruby
170
+ redirect_to_provider @strategy, redirect_uri: auth_callback_url(params[:provider]),
171
+ params: { invitation: params[:invitation] }
172
+
173
+ auth = authenticate_with_provider(@strategy)
174
+ auth.params["invitation"]
175
+ ```
176
+
177
+ It goes through a cookie as JSON, so its keys come back as strings. Keep it
178
+ small: a cookie holds 4 KB, and a large `params:` raises
179
+ `ActionDispatch::Cookies::CookieOverflow` when the person leaves.
180
+
181
+ ## Connect to a vendor's API
182
+
183
+ The same two helpers connect an account at a vendor, here Shopify, whose
184
+ sign-in needs the shop's address first.
185
+
186
+ ```ruby
187
+ config.provider :shopify, client_id: ENV["SHOPIFY_CLIENT_ID"],
188
+ client_secret: ENV["SHOPIFY_CLIENT_SECRET"], scope: "read_orders"
189
+ ```
190
+
191
+ ### Ask for the fields
192
+
193
+ A strategy is an ActiveModel. Its attributes are what a person types before
194
+ signing in:
195
+
196
+ ```ruby
197
+ AnyAuth.strategy_class(:shopify).attribute_names # => ["shop"]
198
+ ```
199
+
200
+ ```erb
201
+ <%= form_with model: @strategy, scope: :strategy, url: shops_path do |form| %>
202
+ <%= form.label :shop %>
203
+ <%= form.text_field :shop %>
204
+ <%= tag.p @strategy.errors.full_messages_for(:shop).to_sentence %>
205
+ <%= form.submit "Connect" %>
206
+ <% end %>
207
+ ```
208
+
209
+ ```ruby
210
+ # config/routes.rb
211
+ resources :shops, only: %i[ index new create ]
212
+ namespace :shops do
213
+ resource :callback, only: :show
214
+ end
215
+ ```
216
+
217
+ ```ruby
218
+ # app/controllers/shops_controller.rb
219
+ class ShopsController < ApplicationController
220
+ include AnyAuth::ControllerHelpers
221
+
222
+ def new
223
+ @strategy = AnyAuth.strategy(:shopify)
224
+ end
225
+
226
+ def create
227
+ @strategy = AnyAuth.strategy(:shopify, params.expect(strategy: [ :shop ]))
228
+
229
+ if @strategy.valid?
230
+ redirect_to_provider @strategy, redirect_uri: shops_callback_url
231
+ else
232
+ render :new, status: :unprocessable_content
233
+ end
234
+ end
235
+ end
236
+ ```
237
+
238
+ ```ruby
239
+ # app/controllers/shops/callbacks_controller.rb
240
+ class Shops::CallbacksController < ApplicationController
241
+ include AnyAuth::ControllerHelpers
242
+
243
+ def show
244
+ shopify = AnyAuth.strategy(:shopify)
245
+ auth = authenticate_with_provider(shopify)
246
+
247
+ Current.user.shops.create!(credentials: shopify.attributes.merge(auth.credentials))
248
+ redirect_to shops_path, notice: "#{shopify.shop} is connected."
249
+ end
250
+ end
251
+ ```
252
+
253
+ `authenticate_with_provider` puts the shop back on the strategy, so
254
+ `shopify.attributes` is what was typed. Permit the attribute names and nothing
255
+ else. `Economic` and `Adversus` have fields and no sign-in at all: check
256
+ `valid?` and store `strategy.attributes`.
257
+
258
+ ### Store and refresh the credentials
259
+
260
+ Store `auth.credentials` (encrypted), and renew it before each use:
261
+
262
+ ```ruby
263
+ class Shop < ApplicationRecord
264
+ serialize :credentials, coder: JSON
265
+ encrypts :credentials
266
+
267
+ def access_token
268
+ renewed = strategy.refresh(credentials)
269
+ update!(credentials: renewed) if renewed != credentials
270
+ renewed["access_token"]
271
+ end
272
+
273
+ private
274
+ def strategy
275
+ AnyAuth.strategy(:shopify, shop: credentials["shop"])
276
+ end
277
+ end
278
+ ```
279
+
280
+ `refresh` asks the vendor only when the token runs out within two minutes, and
281
+ keeps a refresh token the vendor did not replace. A vendor that rotates its
282
+ refresh token, as Shopify does, must not be refreshed twice at once. How a
283
+ vendor wants the token sent on an API call is on its
284
+ [strategy page](docs/strategies).
285
+
286
+ ### Configuring each sign-in (OmniAuth's setup phase)
287
+
288
+ OmniAuth runs a `setup` proc before each phase to change a strategy's options
289
+ for that request, such as a customer's own client or IdP. In AnyAuth you build
290
+ the strategy yourself, so the setup is the arguments you build it with.
291
+ Options given to `AnyAuth.strategy` win over the configured ones:
292
+
293
+ ```ruby
294
+ config.provider :shopify, scope: "read_orders"
295
+ ```
296
+
297
+ ```ruby
298
+ class Auth::BaseController < ApplicationController
299
+ # …
300
+
301
+ private
302
+ def set_strategy
303
+ @strategy = AnyAuth.strategy(params[:provider], **Current.account.sign_in_options)
304
+ end
305
+ end
306
+ ```
307
+
308
+ Build it the same way in both actions; a `before_action` does that. Only the
309
+ strategy's fields (such as Shopify's shop) travel to the callback with the
310
+ sign-in. Its options do not, so a client id or certificate from your database
311
+ must be looked up again, as above.
312
+
313
+ ## Reference
314
+
315
+ ### Providers
316
+
317
+ ```ruby
318
+ config.provider :google, client_id: -> { ENV["GOOGLE_CLIENT_ID"] }
319
+ config.provider :google_drive, from: :google, scope: "https://www.googleapis.com/auth/drive.file"
320
+ config.provider :google_workspace, strategy: :google, client_id: "…", client_secret: "…"
321
+
322
+ AnyAuth.providers # => ["google", "google_drive", "google_workspace"]
323
+ ```
324
+
325
+ | | |
326
+ | --- | --- |
327
+ | `from:` | another provider's strategy and options, here the same Google client asking for Drive |
328
+ | `strategy:` | another provider's code only, with options of its own |
329
+ | a callable value | asked each time a strategy is built |
330
+ | `scope:` | replaces the strategy's default; OpenID Connect always adds `openid` |
331
+
332
+ Options sent to the vendor are declared per strategy (`scope` everywhere,
333
+ `prompt` and `login_hint` for Google and Microsoft, and others on each
334
+ strategy page). An unknown option raises `ActiveModel::UnknownAttributeError`
335
+ when the strategy is built.
336
+
337
+ ### Controller helpers
338
+
339
+ | | |
340
+ | --- | --- |
341
+ | `redirect_to_provider(strategy, redirect_uri:, params: {})` | keeps the sign-in in its own cookie and redirects to the vendor |
342
+ | `authenticate_with_provider(strategy)` | checks the callback, swaps the code and returns the `auth` |
343
+ | `any_auth_params(strategy)` | the `params:` you passed, readable before the code is swapped and when the sign-in fails |
344
+ | `delete_any_auth_cookie` | forgets a sign-in under way; call it when someone signs out |
345
+
346
+ The sign-in is kept for ten minutes and used once. One at a time: a second
347
+ replaces the first. It lives in its own cookie rather than the session, so
348
+ `reset_session` leaves it; call `delete_any_auth_cookie` on sign-out so the
349
+ next person at the browser cannot finish it.
350
+
351
+ ### What comes back
352
+
353
+ | | |
354
+ | --- | --- |
355
+ | `auth.provider` | the name the provider is configured under |
356
+ | `auth.uid` | who the vendor's token is for, as the vendor identifies them |
357
+ | `auth.info` | `name`, `email`, `image`, nil where the vendor does not say; `email_verified`, false unless it vouches |
358
+ | `auth.credentials` | `access_token`, and `refresh_token` and `expires_at` (ISO 8601) when sent |
359
+ | `auth.raw` | what the vendor said about who signed in: the ID token's claims, or its answer without the tokens |
360
+ | `auth.params` | what you passed as `params:` |
361
+
362
+ What `uid` is, and what each vendor puts in `raw`, is on its
363
+ [strategy page](docs/strategies).
364
+
365
+ ### Errors
366
+
367
+ ```
368
+ AnyAuth::Error
369
+ ├── AnyAuth::AuthenticationError the sign-in or refresh didn't work: rescue this
370
+ │ ├── InvalidCallback the answer can't be proven ours
371
+ │ ├── AccessDenied the person or the vendor said no, or the grant is dead
372
+ │ └── Unavailable the vendor couldn't answer now
373
+ └── AnyAuth::ConfigurationError the vendor says your setup is wrong: let it raise
374
+ ```
375
+
376
+ | Error | Means | Next |
377
+ | --- | --- | --- |
378
+ | `InvalidCallback` | wrong state, a bad signature or ID token, no code, nothing under way | start again |
379
+ | `AccessDenied` | `access_denied`, `invalid_grant`, `unauthorized_client`, `invalid_scope`, a refused refresh | sign in again |
380
+ | `Unavailable` | a timeout, a server error, a rate limit, an answer that cannot be read | try again later |
381
+ | `ConfigurationError` | `invalid_client`, `invalid_request`, an unsupported grant or response type | fix the setup |
382
+
383
+ Every error carries what the vendor said: `code` (its own word, such as
384
+ `invalid_grant`, or nil), `description` (its explanation, for logs; never show
385
+ it to people, it can be forged) and `retry_after` (seconds, when the vendor
386
+ says when to try again). `reason` is the vendor's code, or the kind of
387
+ failure when it gave none: `invalid_callback`, `access_denied`, `unavailable`.
388
+
389
+ ```ruby
390
+ rescue_from AnyAuth::AuthenticationError, with: :refused
391
+ rescue_from AnyAuth::Unavailable, with: :try_again_later
392
+
393
+ # a background refresh
394
+ retry_on AnyAuth::Unavailable, wait: ->(executions, error) { error.retry_after || executions**4 }
395
+ ```
396
+
397
+ Mistakes AnyAuth can see before asking anyone are ordinary Ruby errors: an
398
+ unconfigured provider is a `KeyError`, a missing `client_id` an `ArgumentError`.
399
+
400
+ ### A failure page, as with OmniAuth
401
+
402
+ To send every failed sign-in to one page, as OmniAuth's `/auth/failure` does,
403
+ write the rescue once in the controller that signs people in:
404
+
405
+ ```ruby
406
+ rescue_from AnyAuth::AuthenticationError, with: :redirect_to_failure
407
+
408
+ private
409
+ def redirect_to_failure(error)
410
+ Rails.error.report(error, handled: true)
411
+ redirect_to auth_failure_path(message: error.reason, provider: params[:provider])
412
+ end
413
+ ```
414
+
415
+ ```ruby
416
+ # config/routes.rb
417
+ get "auth/failure", to: "auth/failures#show", as: :auth_failure
418
+ ```
419
+
420
+ Keep `error.description` out of the
421
+ address: it is the vendor's text, for logs. Unlike OmniAuth's failure page,
422
+ this never receives a `ConfigurationError`, and it behaves the same in every
423
+ environment.
424
+
425
+ ### Strategies
426
+
427
+ | Strategy | Kind | |
428
+ | --- | --- | --- |
429
+ | [`Google`](docs/strategies/google.md) | OpenID Connect | sign-in and Google APIs |
430
+ | [`Microsoft`](docs/strategies/microsoft.md) | OpenID Connect | work, school and personal accounts |
431
+ | [`Apple`](docs/strategies/apple.md) | OpenID Connect | signed client secret; the callback is a `POST` |
432
+ | [`Hubspot`](docs/strategies/hubspot.md) | OAuth 2 | one more request, to name the user |
433
+ | [`Relatel`](docs/strategies/relatel.md) | OAuth 2 | one more request, to name the employee |
434
+ | [`Tavle`](docs/strategies/tavle.md) | OAuth 2 | one more request, to name the member |
435
+ | [`Shopify`](docs/strategies/shopify.md) | OAuth 2 with a field | per-shop endpoints, signed callback |
436
+ | [`Signicat`](docs/strategies/signicat.md) | OpenID Connect | national eIDs, with the eID and level checked |
437
+ | [`Economic`](docs/strategies/economic.md), [`Adversus`](docs/strategies/adversus.md) | fields only | |
438
+ | [`Saml`](docs/strategies/saml.md) | SAML 2.0 | a customer's IdP; needs ruby-saml, loaded on request |
439
+ | [`OAuth1`](docs/adding-a-strategy.md#an-oauth-1-vendor) | OAuth 1.0a | a base for OAuth 1 vendors; needs the oauth gem, loaded on request |
440
+ | [`Developer`](docs/strategies/developer.md) | a field | sign in as anyone; development only, loaded on request |
441
+
442
+ ## Writing a strategy
443
+
444
+ A new OAuth 2 vendor is its endpoints and one request to learn who signed in:
445
+
446
+ ```ruby
447
+ class Pipedrive < AnyAuth::Strategies::OAuth2
448
+ def client_options
449
+ { site: "https://api.pipedrive.com", authorize_url: "https://oauth.pipedrive.com/oauth/authorize",
450
+ token_url: "https://oauth.pipedrive.com/oauth/token" }
451
+ end
452
+
453
+ private
454
+
455
+ def identity(access_token, _session)
456
+ user = get(access_token, "/v1/users/me")["data"]
457
+ { uid: user["id"].to_s, info: AnyAuth::Info.new(name: user["name"], email: user["email"]) }
458
+ end
459
+ end
460
+ ```
461
+
462
+ [Adding a strategy](docs/adding-a-strategy.md) covers OpenID Connect vendors,
463
+ fields, PKCE, the steps you can override and how to test it.
464
+ [How a sign-in works](docs/how-a-sign-in-works.md) says what is kept and
465
+ checked along the way.
466
+
467
+ ## Coming from OmniAuth
468
+
469
+ | OmniAuth | AnyAuth |
470
+ | --- | --- |
471
+ | `provider :google_oauth2, id, secret` | `config.provider :google, client_id:, client_secret:` |
472
+ | `/auth/:provider` and its callback, by the middleware | two routes and actions of your own |
473
+ | `request.env["omniauth.auth"]` | the return value of `authenticate_with_provider` |
474
+ | `omniauth.params`, `omniauth.origin` | `params:`, read back as `auth.params` |
475
+ | `/auth/failure` | `rescue_from AnyAuth::AuthenticationError`, or [a failure page of your own](#a-failure-page-as-with-omniauth) |
476
+ | a `setup` proc | [the arguments you build the strategy with](#configuring-each-sign-in-omniauths-setup-phase) |
477
+ | `extra.raw_info` | `auth.raw` |
478
+
479
+ - Keep your provider names: `config.provider :google_oauth2, strategy: :google`.
480
+ - Compare `uid`s before switching; each strategy page says what it is.
481
+ - `auth` is an object: `auth.uid`, not `auth["uid"]`. `credentials` has
482
+ `access_token` where OmniAuth has `token`, and `expires_at` as ISO 8601 text.
483
+
484
+ ## Testing
485
+
486
+ Stub the vendor's HTTP answers and drive your controllers:
487
+
488
+ ```ruby
489
+ post auth_authorization_path(:google)
490
+ sent = Rack::Utils.parse_query(URI(response.location).query)
491
+
492
+ claims = { sub: "g-1", email: "mette@gmail.com", email_verified: true, iss: "https://accounts.google.com",
493
+ aud: "your-client-id", exp: 1.hour.from_now.to_i, nonce: sent["nonce"] }
494
+ stub_request(:post, "https://oauth2.googleapis.com/token").to_return(
495
+ headers: { "Content-Type" => "application/json" },
496
+ body: { access_token: "token", id_token: JWT.encode(claims, nil, "none") }.to_json
497
+ )
498
+
499
+ get auth_callback_path(:google, code: "code", state: sent["state"])
500
+ ```
501
+
502
+ For development, the [`Developer`](docs/strategies/developer.md) strategy signs
503
+ in as any email without a vendor.
504
+
505
+ ## Without the helpers
506
+
507
+ Outside a controller, call `request_phase` and `callback_phase` yourself; see
508
+ [How a sign-in works](docs/how-a-sign-in-works.md#without-the-helpers).
509
+
510
+ ## Limits
511
+
512
+ - A callback that arrives as a cross-site `POST` (Apple, SAML) needs HTTPS,
513
+ so the sign-in's cookie can come back with it.
514
+ - Endpoints are written in each strategy; there is no discovery.
515
+ - The ID token is read from the token endpoint over TLS and checked for
516
+ issuer, audience, expiry and nonce. Its signature is not verified, which
517
+ OpenID Connect allows for that path only.
518
+ - `info` is a name, an email, whether it is vouched for, and a picture.
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AnyAuth
4
+ Auth = Data.define(:provider, :uid, :info, :credentials, :raw, :params) do
5
+ def initialize(provider:, credentials:, uid: nil, info: Info.new, raw: {}, params: {})
6
+ super
7
+ end
8
+
9
+ def inspect
10
+ "#<data #{self.class.name} provider=#{provider.inspect}, uid=#{uid.inspect}>"
11
+ end
12
+
13
+ def pretty_print(printer)
14
+ printer.text(inspect)
15
+ end
16
+
17
+ def as_json(*)
18
+ to_h.except(:credentials).as_json
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AnyAuth
4
+ class Configuration
5
+ def initialize
6
+ @entries = {}
7
+ end
8
+
9
+ def provider(name, strategy: nil, from: nil, **options)
10
+ if from
11
+ strategy ||= strategy_class(from)
12
+ options = entry_for(from)[:options].merge(options)
13
+ end
14
+
15
+ @entries[name.to_s] = { strategy_class: class_named(strategy || name), options: }
16
+ end
17
+
18
+ def providers
19
+ @entries.keys
20
+ end
21
+
22
+ def strategy_class(name)
23
+ entry_for(name)[:strategy_class]
24
+ end
25
+
26
+ def strategy(name, attributes = {})
27
+ strategy = strategy_class(name).new(defaults_for(name))
28
+ strategy.assign_attributes(attributes)
29
+ strategy.provider = name.to_s
30
+ strategy
31
+ end
32
+
33
+ private
34
+
35
+ def entry_for(name)
36
+ @entries.fetch(name.to_s)
37
+ end
38
+
39
+ def class_named(strategy)
40
+ return strategy if strategy.is_a?(Class)
41
+
42
+ Strategies.const_get(strategy.to_s.underscore.camelize, false)
43
+ end
44
+
45
+ def defaults_for(name)
46
+ entry_for(name)[:options].transform_values { resolve(it) }
47
+ end
48
+
49
+ def resolve(value)
50
+ return value.call if value.respond_to?(:call)
51
+
52
+ value
53
+ end
54
+ end
55
+ end