stytch 6.4.0 → 9.8.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/.github/workflows/ruby.yml +13 -0
- data/.gitignore +2 -0
- data/.rubocop.yml +22 -0
- data/DEVELOPMENT.md +5 -2
- data/README.md +52 -3
- data/lib/stytch/b2b_client.rb +18 -3
- data/lib/stytch/b2b_discovery.rb +73 -33
- data/lib/stytch/b2b_magic_links.rb +63 -24
- data/lib/stytch/b2b_oauth.rb +31 -16
- data/lib/stytch/b2b_organizations.rb +788 -51
- data/lib/stytch/b2b_otp.rb +35 -10
- data/lib/stytch/b2b_passwords.rb +141 -44
- data/lib/stytch/b2b_rbac.rb +47 -0
- data/lib/stytch/b2b_recovery_codes.rb +196 -0
- data/lib/stytch/b2b_scim.rb +496 -0
- data/lib/stytch/b2b_sessions.rb +299 -15
- data/lib/stytch/b2b_sso.rb +486 -24
- data/lib/stytch/b2b_totps.rb +255 -0
- data/lib/stytch/client.rb +6 -3
- data/lib/stytch/crypto_wallets.rb +19 -4
- data/lib/stytch/errors.rb +21 -0
- data/lib/stytch/m2m.rb +80 -19
- data/lib/stytch/magic_links.rb +20 -12
- data/lib/stytch/method_options.rb +22 -0
- data/lib/stytch/oauth.rb +10 -4
- data/lib/stytch/otps.rb +27 -17
- data/lib/stytch/passwords.rb +67 -19
- data/lib/stytch/project.rb +26 -0
- data/lib/stytch/rbac_local.rb +58 -0
- data/lib/stytch/request_helper.rb +12 -8
- data/lib/stytch/sessions.rb +131 -31
- data/lib/stytch/totps.rb +9 -5
- data/lib/stytch/users.rb +30 -16
- data/lib/stytch/version.rb +1 -1
- data/lib/stytch/webauthn.rb +126 -24
- data/lib/stytch.rb +1 -0
- data/stytch.gemspec +2 -0
- metadata +42 -6
data/lib/stytch/b2b_sessions.rb
CHANGED
@@ -6,14 +6,51 @@
|
|
6
6
|
# or your changes may be overwritten later!
|
7
7
|
# !!!
|
8
8
|
|
9
|
+
require 'jwt'
|
10
|
+
require 'json/jwt'
|
11
|
+
require_relative 'errors'
|
9
12
|
require_relative 'request_helper'
|
10
13
|
|
11
14
|
module StytchB2B
|
12
15
|
class Sessions
|
16
|
+
class RevokeRequestOptions
|
17
|
+
# Optional authorization object.
|
18
|
+
# Pass in an active Stytch Member session token or session JWT and the request
|
19
|
+
# will be run using that member's permissions.
|
20
|
+
attr_accessor :authorization
|
21
|
+
|
22
|
+
def initialize(
|
23
|
+
authorization: nil
|
24
|
+
)
|
25
|
+
@authorization = authorization
|
26
|
+
end
|
27
|
+
|
28
|
+
def to_headers
|
29
|
+
headers = {}
|
30
|
+
headers.merge!(@authorization.to_headers) if authorization
|
31
|
+
headers
|
32
|
+
end
|
33
|
+
end
|
34
|
+
|
13
35
|
include Stytch::RequestHelper
|
14
36
|
|
15
|
-
def initialize(connection)
|
37
|
+
def initialize(connection, project_id, policy_cache)
|
16
38
|
@connection = connection
|
39
|
+
|
40
|
+
@policy_cache = policy_cache
|
41
|
+
@project_id = project_id
|
42
|
+
@cache_last_update = 0
|
43
|
+
@jwks_loader = lambda do |options|
|
44
|
+
@cached_keys = nil if options[:invalidate] && @cache_last_update < Time.now.to_i - 300
|
45
|
+
@cached_keys ||= begin
|
46
|
+
@cache_last_update = Time.now.to_i
|
47
|
+
keys = []
|
48
|
+
get_jwks(project_id: @project_id)['keys'].each do |r|
|
49
|
+
keys << r
|
50
|
+
end
|
51
|
+
{ keys: keys }
|
52
|
+
end
|
53
|
+
end
|
17
54
|
end
|
18
55
|
|
19
56
|
# Retrieves all active Sessions for a Member.
|
@@ -41,17 +78,25 @@ module StytchB2B
|
|
41
78
|
organization_id:,
|
42
79
|
member_id:
|
43
80
|
)
|
81
|
+
headers = {}
|
44
82
|
query_params = {
|
45
83
|
organization_id: organization_id,
|
46
84
|
member_id: member_id
|
47
85
|
}
|
48
86
|
request = request_with_query_params('/v1/b2b/sessions', query_params)
|
49
|
-
get_request(request)
|
87
|
+
get_request(request, headers)
|
50
88
|
end
|
51
89
|
|
52
90
|
# Authenticates a Session and updates its lifetime by the specified `session_duration_minutes`. If the `session_duration_minutes` is not specified, a Session will not be extended. This endpoint requires either a `session_jwt` or `session_token` be included in the request. It will return an error if both are present.
|
53
91
|
#
|
54
|
-
# You may provide a JWT that needs to be refreshed and is expired according to its `exp` claim. A new JWT will be returned if both the signature and the underlying Session are still valid.
|
92
|
+
# You may provide a JWT that needs to be refreshed and is expired according to its `exp` claim. A new JWT will be returned if both the signature and the underlying Session are still valid. See our [How to use Stytch Session JWTs](https://stytch.com/docs/b2b/guides/sessions/resources/using-jwts) guide for more information.
|
93
|
+
#
|
94
|
+
# If an `authorization_check` object is passed in, this method will also check if the Member is authorized to perform the given action on the given Resource in the specified. A is authorized if their Member Session contains a Role, assigned [explicitly or implicitly](https://stytch.com/docs/b2b/guides/rbac/role-assignment), with adequate permissions.
|
95
|
+
# In addition, the `organization_id` passed in the authorization check must match the Member's Organization.
|
96
|
+
#
|
97
|
+
# If the Member is not authorized to perform the specified action on the specified Resource, or if the
|
98
|
+
# `organization_id` does not match the Member's Organization, a 403 error will be thrown.
|
99
|
+
# Otherwise, the response will contain a list of Roles that satisfied the authorization check.
|
55
100
|
#
|
56
101
|
# == Parameters:
|
57
102
|
# session_token::
|
@@ -78,6 +123,21 @@ module StytchB2B
|
|
78
123
|
# delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored.
|
79
124
|
# Total custom claims size cannot exceed four kilobytes.
|
80
125
|
# The type of this field is nilable +object+.
|
126
|
+
# authorization_check::
|
127
|
+
# If an `authorization_check` object is passed in, this endpoint will also check if the Member is
|
128
|
+
# authorized to perform the given action on the given Resource in the specified Organization. A Member is authorized if
|
129
|
+
# their Member Session contains a Role, assigned
|
130
|
+
# [explicitly or implicitly](https://stytch.com/docs/b2b/guides/rbac/role-assignment), with adequate permissions.
|
131
|
+
# In addition, the `organization_id` passed in the authorization check must match the Member's Organization.
|
132
|
+
#
|
133
|
+
# The Roles on the Member Session may differ from the Roles you see on the Member object - Roles that are implicitly
|
134
|
+
# assigned by SSO connection or SSO group will only be valid for a Member Session if there is at least one authentication
|
135
|
+
# factor on the Member Session from the specified SSO connection.
|
136
|
+
#
|
137
|
+
# If the Member is not authorized to perform the specified action on the specified Resource, or if the
|
138
|
+
# `organization_id` does not match the Member's Organization, a 403 error will be thrown.
|
139
|
+
# Otherwise, the response will contain a list of Roles that satisfied the authorization check.
|
140
|
+
# The type of this field is nilable +AuthorizationCheck+ (+object+).
|
81
141
|
#
|
82
142
|
# == Returns:
|
83
143
|
# An object with the following fields:
|
@@ -102,19 +162,26 @@ module StytchB2B
|
|
102
162
|
# status_code::
|
103
163
|
# The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
|
104
164
|
# The type of this field is +Integer+.
|
165
|
+
# verdict::
|
166
|
+
# If an `authorization_check` is provided in the request and the check succeeds, this field will return
|
167
|
+
# the complete list of Roles that gave the Member permission to perform the specified action on the specified Resource.
|
168
|
+
# The type of this field is nilable +AuthorizationVerdict+ (+object+).
|
105
169
|
def authenticate(
|
106
170
|
session_token: nil,
|
107
171
|
session_duration_minutes: nil,
|
108
172
|
session_jwt: nil,
|
109
|
-
session_custom_claims: nil
|
173
|
+
session_custom_claims: nil,
|
174
|
+
authorization_check: nil
|
110
175
|
)
|
176
|
+
headers = {}
|
111
177
|
request = {}
|
112
178
|
request[:session_token] = session_token unless session_token.nil?
|
113
179
|
request[:session_duration_minutes] = session_duration_minutes unless session_duration_minutes.nil?
|
114
180
|
request[:session_jwt] = session_jwt unless session_jwt.nil?
|
115
181
|
request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
|
182
|
+
request[:authorization_check] = authorization_check unless authorization_check.nil?
|
116
183
|
|
117
|
-
post_request('/v1/b2b/sessions/authenticate', request)
|
184
|
+
post_request('/v1/b2b/sessions/authenticate', request, headers)
|
118
185
|
end
|
119
186
|
|
120
187
|
# Revoke a Session and immediately invalidate all its tokens. To revoke a specific Session, pass either the `member_session_id`, `session_token`, or `session_jwt`. To revoke all Sessions for a Member, pass the `member_id`.
|
@@ -141,27 +208,35 @@ module StytchB2B
|
|
141
208
|
# status_code::
|
142
209
|
# The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
|
143
210
|
# The type of this field is +Integer+.
|
211
|
+
#
|
212
|
+
# == Method Options:
|
213
|
+
# This method supports an optional +StytchB2B::Sessions::RevokeRequestOptions+ object which will modify the headers sent in the HTTP request.
|
144
214
|
def revoke(
|
145
215
|
member_session_id: nil,
|
146
216
|
session_token: nil,
|
147
217
|
session_jwt: nil,
|
148
|
-
member_id: nil
|
218
|
+
member_id: nil,
|
219
|
+
method_options: nil
|
149
220
|
)
|
221
|
+
headers = {}
|
222
|
+
headers = headers.merge(method_options.to_headers) unless method_options.nil?
|
150
223
|
request = {}
|
151
224
|
request[:member_session_id] = member_session_id unless member_session_id.nil?
|
152
225
|
request[:session_token] = session_token unless session_token.nil?
|
153
226
|
request[:session_jwt] = session_jwt unless session_jwt.nil?
|
154
227
|
request[:member_id] = member_id unless member_id.nil?
|
155
228
|
|
156
|
-
post_request('/v1/b2b/sessions/revoke', request)
|
229
|
+
post_request('/v1/b2b/sessions/revoke', request, headers)
|
157
230
|
end
|
158
231
|
|
159
|
-
# Use this endpoint to exchange a
|
232
|
+
# Use this endpoint to exchange a's existing session for another session in a different. This can be used to accept an invite, but not to create a new member via domain matching.
|
160
233
|
#
|
161
234
|
# To create a new member via domain matching, use the [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) flow instead.
|
162
235
|
#
|
163
236
|
# Only Email Magic Link, OAuth, and SMS OTP factors can be transferred between sessions. Other authentication factors, such as password factors, will not be transferred to the new session.
|
237
|
+
# Any OAuth Tokens owned by the Member will not be transferred to the new Organization.
|
164
238
|
# SMS OTP factors can be used to fulfill MFA requirements for the target Organization if both the original and target Member have the same phone number and the phone number is verified for both Members.
|
239
|
+
# HubSpot and Slack OAuth registrations will not be transferred between sessions. Instead, you will receive a corresponding factor with type `"oauth_exchange_slack"` or `"oauth_exchange_hubspot"`
|
165
240
|
#
|
166
241
|
# If the Member is required to complete MFA to log in to the Organization, the returned value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned.
|
167
242
|
# The `intermediate_session_token` can be passed into the [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the MFA step and acquire a full member session.
|
@@ -197,7 +272,7 @@ module StytchB2B
|
|
197
272
|
# Total custom claims size cannot exceed four kilobytes.
|
198
273
|
# The type of this field is nilable +object+.
|
199
274
|
# locale::
|
200
|
-
# If the
|
275
|
+
# If the needs to complete an MFA step, and the Member has a phone number, this endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale argument will be used to determine which language to use when sending the passcode.
|
201
276
|
#
|
202
277
|
# Parameter is a [IETF BCP 47 language tag](https://www.w3.org/International/articles/language-tags/), e.g. `"en"`.
|
203
278
|
#
|
@@ -234,10 +309,7 @@ module StytchB2B
|
|
234
309
|
# Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step to log in to the Organization.
|
235
310
|
# The type of this field is +Boolean+.
|
236
311
|
# intermediate_session_token::
|
237
|
-
# The returned Intermediate Session Token contains any Email Magic Link or OAuth factors from the original member session that are valid for the target Organization.
|
238
|
-
# The token can be used with the [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the MFA flow and log in to the target Organization.
|
239
|
-
# It can also be used with the [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) to join a different existing Organization,
|
240
|
-
# or the [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization.
|
312
|
+
# The returned Intermediate Session Token contains any Email Magic Link or OAuth factors from the original member session that are valid for the target Organization. If this value is non-empty, the member must complete an MFA step to finish logging in to the Organization. The token can be used with the [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms), [TOTP Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-totp), or [Recovery Codes Recover endpoint](https://stytch.com/docs/b2b/api/recovery-codes-recover) to complete an MFA flow and log in to the Organization. It can also be used with the [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) to join a specific Organization that allows the factors represented by the intermediate session token; or the [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member.
|
241
313
|
# The type of this field is +String+.
|
242
314
|
# status_code::
|
243
315
|
# The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
|
@@ -245,6 +317,9 @@ module StytchB2B
|
|
245
317
|
# mfa_required::
|
246
318
|
# Information about the MFA requirements of the Organization and the Member's options for fulfilling MFA.
|
247
319
|
# The type of this field is nilable +MfaRequired+ (+object+).
|
320
|
+
# primary_required::
|
321
|
+
# (no documentation yet)
|
322
|
+
# The type of this field is nilable +PrimaryRequired+ (+object+).
|
248
323
|
def exchange(
|
249
324
|
organization_id:,
|
250
325
|
session_token: nil,
|
@@ -253,6 +328,7 @@ module StytchB2B
|
|
253
328
|
session_custom_claims: nil,
|
254
329
|
locale: nil
|
255
330
|
)
|
331
|
+
headers = {}
|
256
332
|
request = {
|
257
333
|
organization_id: organization_id
|
258
334
|
}
|
@@ -262,11 +338,92 @@ module StytchB2B
|
|
262
338
|
request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
|
263
339
|
request[:locale] = locale unless locale.nil?
|
264
340
|
|
265
|
-
post_request('/v1/b2b/sessions/exchange', request)
|
341
|
+
post_request('/v1/b2b/sessions/exchange', request, headers)
|
342
|
+
end
|
343
|
+
|
344
|
+
# Migrate a session from an external OIDC compliant endpoint. Stytch will call the external UserInfo endpoint defined in your Stytch Project settings in the [Dashboard](/dashboard), and then perform a lookup using the `session_token`. If the response contains a valid email address, Stytch will attempt to match that email address with an existing in your and create a Stytch Session. You will need to create the member before using this endpoint.
|
345
|
+
#
|
346
|
+
# == Parameters:
|
347
|
+
# session_token::
|
348
|
+
# The authorization token Stytch will pass in to the external userinfo endpoint.
|
349
|
+
# The type of this field is +String+.
|
350
|
+
# organization_id::
|
351
|
+
# Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to perform operations on an Organization, so be sure to preserve this value.
|
352
|
+
# The type of this field is +String+.
|
353
|
+
# session_duration_minutes::
|
354
|
+
# Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't already exist,
|
355
|
+
# returning both an opaque `session_token` and `session_jwt` for this session. Remember that the `session_jwt` will have a fixed lifetime of
|
356
|
+
# five minutes regardless of the underlying session duration, and will need to be refreshed over time.
|
357
|
+
#
|
358
|
+
# This value must be a minimum of 5 and a maximum of 527040 minutes (366 days).
|
359
|
+
#
|
360
|
+
# If a `session_token` or `session_jwt` is provided then a successful authentication will continue to extend the session this many minutes.
|
361
|
+
#
|
362
|
+
# If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 minute duration. If you don't want
|
363
|
+
# to use the Stytch session product, you can ignore the session fields in the response.
|
364
|
+
# The type of this field is nilable +Integer+.
|
365
|
+
# session_custom_claims::
|
366
|
+
# Add a custom claims map to the Session being authenticated. Claims are only created if a Session is initialized by providing a value in
|
367
|
+
# `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a key in an existing Session, supply a new value. To
|
368
|
+
# delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored.
|
369
|
+
# Total custom claims size cannot exceed four kilobytes.
|
370
|
+
# The type of this field is nilable +object+.
|
371
|
+
#
|
372
|
+
# == Returns:
|
373
|
+
# An object with the following fields:
|
374
|
+
# request_id::
|
375
|
+
# Globally unique UUID that is returned with every API call. This value is important to log for debugging purposes; we may ask for this value to help identify a specific API call when helping you debug an issue.
|
376
|
+
# The type of this field is +String+.
|
377
|
+
# member_id::
|
378
|
+
# Globally unique UUID that identifies a specific Member.
|
379
|
+
# The type of this field is +String+.
|
380
|
+
# session_token::
|
381
|
+
# A secret token for a given Stytch Session.
|
382
|
+
# The type of this field is +String+.
|
383
|
+
# session_jwt::
|
384
|
+
# The JSON Web Token (JWT) for a given Stytch Session.
|
385
|
+
# The type of this field is +String+.
|
386
|
+
# member::
|
387
|
+
# The [Member object](https://stytch.com/docs/b2b/api/member-object)
|
388
|
+
# The type of this field is +Member+ (+object+).
|
389
|
+
# organization::
|
390
|
+
# The [Organization object](https://stytch.com/docs/b2b/api/organization-object).
|
391
|
+
# The type of this field is +Organization+ (+object+).
|
392
|
+
# status_code::
|
393
|
+
# (no documentation yet)
|
394
|
+
# The type of this field is +Integer+.
|
395
|
+
# member_session::
|
396
|
+
# The [Session object](https://stytch.com/docs/b2b/api/session-object).
|
397
|
+
# The type of this field is nilable +MemberSession+ (+object+).
|
398
|
+
def migrate(
|
399
|
+
session_token:,
|
400
|
+
organization_id:,
|
401
|
+
session_duration_minutes: nil,
|
402
|
+
session_custom_claims: nil
|
403
|
+
)
|
404
|
+
headers = {}
|
405
|
+
request = {
|
406
|
+
session_token: session_token,
|
407
|
+
organization_id: organization_id
|
408
|
+
}
|
409
|
+
request[:session_duration_minutes] = session_duration_minutes unless session_duration_minutes.nil?
|
410
|
+
request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
|
411
|
+
|
412
|
+
post_request('/v1/b2b/sessions/migrate', request, headers)
|
266
413
|
end
|
267
414
|
|
268
415
|
# Get the JSON Web Key Set (JWKS) for a project.
|
269
416
|
#
|
417
|
+
# JWKS are rotated every ~6 months. Upon rotation, new JWTs will be signed using the new key set, and both key sets will be returned by this endpoint for a period of 1 month.
|
418
|
+
#
|
419
|
+
# JWTs have a set lifetime of 5 minutes, so there will be a 5 minute period where some JWTs will be signed by the old JWKS, and some JWTs will be signed by the new JWKS. The correct JWKS to use for validation is determined by matching the `kid` value of the JWT and JWKS.
|
420
|
+
#
|
421
|
+
# If you're using one of our [backend SDKs](https://stytch.com/docs/b2b/sdks), the JWKS roll will be handled for you.
|
422
|
+
#
|
423
|
+
# If you're using your own JWT validation library, many have built-in support for JWKS rotation, and you'll just need to supply this API endpoint. If not, your application should decide which JWKS to use for validation by inspecting the `kid` value.
|
424
|
+
#
|
425
|
+
# See our [How to use Stytch Session JWTs](https://stytch.com/docs/b2b/guides/sessions/resources/using-jwts) guide for more information.
|
426
|
+
#
|
270
427
|
# == Parameters:
|
271
428
|
# project_id::
|
272
429
|
# The `project_id` to get the JWKS for.
|
@@ -286,9 +443,136 @@ module StytchB2B
|
|
286
443
|
def get_jwks(
|
287
444
|
project_id:
|
288
445
|
)
|
446
|
+
headers = {}
|
289
447
|
query_params = {}
|
290
448
|
request = request_with_query_params("/v1/b2b/sessions/jwks/#{project_id}", query_params)
|
291
|
-
get_request(request)
|
449
|
+
get_request(request, headers)
|
450
|
+
end
|
451
|
+
|
452
|
+
# MANUAL(Sessions::authenticate_jwt)(SERVICE_METHOD)
|
453
|
+
# ADDIMPORT: require 'jwt'
|
454
|
+
# ADDIMPORT: require 'json/jwt'
|
455
|
+
# ADDIMPORT: require_relative 'errors'
|
456
|
+
|
457
|
+
# Parse a JWT and verify the signature. If max_token_age_seconds is unset, call the API directly
|
458
|
+
# If max_token_age_seconds is set and the JWT was issued (based on the "iat" claim) less than
|
459
|
+
# max_token_age_seconds seconds ago, then just verify locally and don't call the API
|
460
|
+
# To force remote validation for all tokens, set max_token_age_seconds to 0 or call authenticate()
|
461
|
+
# Note that the 'user_id' field of the returned session is DEPRECATED: Use member_id instead
|
462
|
+
# This field will be removed in a future MAJOR release.
|
463
|
+
# If max_token_age_seconds is not supplied 300 seconds will be used as the default.
|
464
|
+
# If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.
|
465
|
+
def authenticate_jwt(
|
466
|
+
session_jwt,
|
467
|
+
max_token_age_seconds: nil,
|
468
|
+
session_duration_minutes: nil,
|
469
|
+
session_custom_claims: nil,
|
470
|
+
authorization_check: nil,
|
471
|
+
clock_tolerance_seconds: nil
|
472
|
+
)
|
473
|
+
max_token_age_seconds = 300 if max_token_age_seconds.nil?
|
474
|
+
clock_tolerance_seconds = 0 if clock_tolerance_seconds.nil?
|
475
|
+
|
476
|
+
if max_token_age_seconds == 0
|
477
|
+
return authenticate(
|
478
|
+
session_jwt: session_jwt,
|
479
|
+
session_duration_minutes: session_duration_minutes,
|
480
|
+
session_custom_claims: session_custom_claims,
|
481
|
+
authorization_check: authorization_check
|
482
|
+
)
|
483
|
+
end
|
484
|
+
|
485
|
+
decoded_jwt = authenticate_jwt_local(session_jwt, max_token_age_seconds: max_token_age_seconds, authorization_check: authorization_check, clock_tolerance_seconds: clock_tolerance_seconds)
|
486
|
+
return decoded_jwt unless decoded_jwt.nil?
|
487
|
+
|
488
|
+
authenticate(
|
489
|
+
session_jwt: session_jwt,
|
490
|
+
session_duration_minutes: session_duration_minutes,
|
491
|
+
session_custom_claims: session_custom_claims,
|
492
|
+
authorization_check: authorization_check
|
493
|
+
)
|
494
|
+
rescue StandardError
|
495
|
+
# JWT could not be verified locally. Check with the Stytch API.
|
496
|
+
authenticate(
|
497
|
+
session_jwt: session_jwt,
|
498
|
+
session_duration_minutes: session_duration_minutes,
|
499
|
+
session_custom_claims: session_custom_claims,
|
500
|
+
authorization_check: authorization_check
|
501
|
+
)
|
502
|
+
end
|
503
|
+
|
504
|
+
# Parse a JWT and verify the signature locally (without calling /authenticate in the API)
|
505
|
+
# Uses the cached value to get the JWK but if it is unavailable, it calls the get_jwks()
|
506
|
+
# function to get the JWK
|
507
|
+
# This method never authenticates a JWT directly with the API
|
508
|
+
# If max_token_age_seconds is not supplied 300 seconds will be used as the default.
|
509
|
+
# If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.
|
510
|
+
def authenticate_jwt_local(session_jwt, max_token_age_seconds: nil, authorization_check: nil, clock_tolerance_seconds: nil)
|
511
|
+
max_token_age_seconds = 300 if max_token_age_seconds.nil?
|
512
|
+
clock_tolerance_seconds = 0 if clock_tolerance_seconds.nil?
|
513
|
+
|
514
|
+
issuer = 'stytch.com/' + @project_id
|
515
|
+
begin
|
516
|
+
decoded_token = JWT.decode session_jwt, nil, true,
|
517
|
+
{ jwks: @jwks_loader, iss: issuer, verify_iss: true, aud: @project_id, verify_aud: true, algorithms: ['RS256'], nbf_leeway: clock_tolerance_seconds }
|
518
|
+
|
519
|
+
session = decoded_token[0]
|
520
|
+
iat_time = Time.at(session['iat']).to_datetime
|
521
|
+
return nil unless iat_time + max_token_age_seconds >= Time.now
|
522
|
+
|
523
|
+
session = marshal_jwt_into_session(session)
|
524
|
+
rescue JWT::InvalidIssuerError
|
525
|
+
raise Stytch::JWTInvalidIssuerError
|
526
|
+
rescue JWT::InvalidAudError
|
527
|
+
raise Stytch::JWTInvalidAudienceError
|
528
|
+
rescue JWT::ExpiredSignature
|
529
|
+
raise Stytch::JWTExpiredSignatureError
|
530
|
+
rescue JWT::IncorrectAlgorithm
|
531
|
+
raise Stytch::JWTIncorrectAlgorithmError
|
532
|
+
end
|
533
|
+
|
534
|
+
# Do the auth check - intentionally don't rescue errors from here
|
535
|
+
if authorization_check && session['roles']
|
536
|
+
@policy_cache.perform_authorization_check(
|
537
|
+
subject_roles: session['roles'],
|
538
|
+
subject_org_id: session['member_session']['organization_id'],
|
539
|
+
authorization_check: authorization_check
|
540
|
+
)
|
541
|
+
end
|
542
|
+
|
543
|
+
session
|
544
|
+
end
|
545
|
+
|
546
|
+
# Note that the 'user_id' field is DEPRECATED: Use member_id instead
|
547
|
+
# This field will be removed in a future MAJOR release.
|
548
|
+
def marshal_jwt_into_session(jwt)
|
549
|
+
stytch_claim = 'https://stytch.com/session'
|
550
|
+
organization_claim = 'https://stytch.com/organization'
|
551
|
+
|
552
|
+
expires_at = jwt[stytch_claim]['expires_at'] || Time.at(jwt['exp']).to_datetime.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
|
553
|
+
# The custom claim set is all the claims in the payload except for the standard claims and
|
554
|
+
# the Stytch session claim. The cleanest way to collect those seems to be naming what we want
|
555
|
+
# to omit and filtering the rest to collect the custom claims.
|
556
|
+
reserved_claims = ['aud', 'exp', 'iat', 'iss', 'jti', 'nbf', 'sub', stytch_claim, organization_claim]
|
557
|
+
custom_claims = jwt.reject { |key, _| reserved_claims.include?(key) }
|
558
|
+
{
|
559
|
+
'member_session' => {
|
560
|
+
'session_id' => jwt[stytch_claim]['id'],
|
561
|
+
'organization_id' => jwt[organization_claim]['organization_id'],
|
562
|
+
'member_id' => jwt['sub'],
|
563
|
+
# DEPRECATED: Use member_id instead
|
564
|
+
'user_id' => jwt['sub'],
|
565
|
+
'started_at' => jwt[stytch_claim]['started_at'],
|
566
|
+
'last_accessed_at' => jwt[stytch_claim]['last_accessed_at'],
|
567
|
+
# For JWTs that include it, prefer the inner expires_at claim.
|
568
|
+
'expires_at' => expires_at,
|
569
|
+
'attributes' => jwt[stytch_claim]['attributes'],
|
570
|
+
'authentication_factors' => jwt[stytch_claim]['authentication_factors'],
|
571
|
+
'custom_claims' => custom_claims
|
572
|
+
},
|
573
|
+
'roles' => jwt[stytch_claim]['roles']
|
574
|
+
}
|
292
575
|
end
|
576
|
+
# ENDMANUAL(Sessions::authenticate_jwt)
|
293
577
|
end
|
294
578
|
end
|