Class: StytchB2B::Sessions

Inherits:
Object
  • Object
show all
Includes:
Stytch::RequestHelper
Defined in:
lib/stytch/b2b_sessions.rb

Instance Method Summary collapse

Methods included from Stytch::RequestHelper

#delete_request, #get_request, #post_request, #put_request, #request_with_query_params

Constructor Details

#initialize(connection, project_id, policy_cache) ⇒ Sessions

Returns a new instance of Sessions.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/stytch/b2b_sessions.rb', line 18

def initialize(connection, project_id, policy_cache)
  @connection = connection

  @policy_cache = policy_cache
  @project_id = project_id
  @cache_last_update = 0
  @jwks_loader = lambda do |options|
    @cached_keys = nil if options[:invalidate] && @cache_last_update < Time.now.to_i - 300
    @cached_keys ||= begin
      @cache_last_update = Time.now.to_i
      keys = []
      get_jwks(project_id: @project_id)['keys'].each do |r|
        keys << r
      end
      { keys: keys }
    end
  end
end

Instance Method Details

#authenticate(session_token: nil, session_duration_minutes: nil, session_jwt: nil, session_custom_claims: nil, authorization_check: nil) ⇒ Object

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.

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.

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 Organization. A Member is authorized if their Member Session contains a Role, assigned [explicitly or implicitly](stytch.com/docs/b2b/guides/rbac/role-assignment), with adequate permissions. In addition, the `organization_id` passed in the authorization check must match the Member’s Organization.

If the Member is not authorized to perform the specified action on the specified Resource, or if the ‘organization_id` does not match the Member’s Organization, a 403 error will be thrown. Otherwise, the response will contain a list of Roles that satisfied the authorization check.

Parameters:

session_token

A secret token for a given Stytch Session. The type of this field is nilable String.

session_duration_minutes

Set the session lifetime to be this many minutes from now. This will start a new session if one doesn’t already exist, returning both an opaque ‘session_token` and `session_jwt` for this session. Remember that the `session_jwt` will have a fixed lifetime of five minutes regardless of the underlying session duration, and will need to be refreshed over time.

This value must be a minimum of 5 and a maximum of 527040 minutes (366 days).

If a ‘session_token` or `session_jwt` is provided then a successful authentication will continue to extend the session this many minutes.

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 to use the Stytch session product, you can ignore the session fields in the response. The type of this field is nilable Integer.

session_jwt

The JSON Web Token (JWT) for a given Stytch Session. The type of this field is nilable String.

session_custom_claims

Add a custom claims map to the Session being authenticated. Claims are only created if a Session is initialized by providing a value in ‘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 delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored. Total custom claims size cannot exceed four kilobytes. The type of this field is nilable object.

authorization_check

If an ‘authorization_check` object is passed in, this endpoint will also check if the Member is authorized to perform the given action on the given Resource in the specified Organization. A Member is authorized if their Member Session contains a Role, assigned [explicitly or implicitly](stytch.com/docs/b2b/guides/rbac/role-assignment), with adequate permissions. In addition, the `organization_id` passed in the authorization check must match the Member’s Organization.

The Roles on the Member Session may differ from the Roles you see on the Member object - Roles that are implicitly assigned by SSO connection or SSO group will only be valid for a Member Session if there is at least one authentication factor on the Member Session from the specified SSO connection.

If the Member is not authorized to perform the specified action on the specified Resource, or if the ‘organization_id` does not match the Member’s Organization, a 403 error will be thrown. Otherwise, the response will contain a list of Roles that satisfied the authorization check. The type of this field is nilable AuthorizationCheck (object).

Returns:

An object with the following fields:

request_id

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. The type of this field is String.

member_session

The [Session object](stytch.com/docs/b2b/api/session-object). The type of this field is MemberSession (object).

session_token

A secret token for a given Stytch Session. The type of this field is String.

session_jwt

The JSON Web Token (JWT) for a given Stytch Session. The type of this field is String.

member

The [Member object](stytch.com/docs/b2b/api/member-object) The type of this field is Member (object).

organization

The [Organization object](stytch.com/docs/b2b/api/organization-object). The type of this field is Organization (object).

status_code

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. The type of this field is Integer.

verdict

If an ‘authorization_check` is provided in the request and the check succeeds, this field will return the complete list of Roles that gave the Member permission to perform the specified action on the specified Resource. The type of this field is nilable AuthorizationVerdict (object).



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/stytch/b2b_sessions.rb', line 150

def authenticate(
  session_token: nil,
  session_duration_minutes: nil,
  session_jwt: nil,
  session_custom_claims: nil,
  authorization_check: nil
)
  headers = {}
  request = {}
  request[:session_token] = session_token unless session_token.nil?
  request[:session_duration_minutes] = session_duration_minutes unless session_duration_minutes.nil?
  request[:session_jwt] = session_jwt unless session_jwt.nil?
  request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
  request[:authorization_check] = authorization_check unless authorization_check.nil?

  post_request('/v1/b2b/sessions/authenticate', request, headers)
end

#authenticate_jwt(session_jwt, max_token_age_seconds: nil, session_duration_minutes: nil, session_custom_claims: nil, authorization_check: nil) ⇒ Object

Parse a JWT and verify the signature. If max_token_age_seconds is unset, call the API directly If max_token_age_seconds is set and the JWT was issued (based on the “iat” claim) less than max_token_age_seconds seconds ago, then just verify locally and don’t call the API To force remote validation for all tokens, set max_token_age_seconds to 0 or call authenticate() Note that the ‘user_id’ field of the returned session is DEPRECATED: Use member_id instead This field will be removed in a future MAJOR release. If max_token_age_seconds is not supplied 300 seconds will be used as the default.



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/stytch/b2b_sessions.rb', line 366

def authenticate_jwt(
  session_jwt,
  max_token_age_seconds: nil,
  session_duration_minutes: nil,
  session_custom_claims: nil,
  authorization_check: nil
)
  max_token_age_seconds = 300 if max_token_age_seconds.nil?

  if max_token_age_seconds == 0
    return authenticate(
      session_jwt: session_jwt,
      session_duration_minutes: session_duration_minutes,
      session_custom_claims: session_custom_claims,
      authorization_check: authorization_check
    )
  end

  decoded_jwt = authenticate_jwt_local(session_jwt, max_token_age_seconds: max_token_age_seconds, authorization_check: authorization_check)
  return decoded_jwt unless decoded_jwt.nil?

  authenticate(
    session_jwt: session_jwt,
    session_duration_minutes: session_duration_minutes,
    session_custom_claims: session_custom_claims,
    authorization_check: authorization_check
  )
rescue StandardError
  # JWT could not be verified locally. Check with the Stytch API.
  authenticate(
    session_jwt: session_jwt,
    session_duration_minutes: session_duration_minutes,
    session_custom_claims: session_custom_claims,
    authorization_check: authorization_check
  )
end

#authenticate_jwt_local(session_jwt, max_token_age_seconds: nil, authorization_check: nil) ⇒ Object

Parse a JWT and verify the signature locally (without calling /authenticate in the API) Uses the cached value to get the JWK but if it is unavailable, it calls the get_jwks() function to get the JWK This method never authenticates a JWT directly with the API If max_token_age_seconds is not supplied 300 seconds will be used as the default.



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/stytch/b2b_sessions.rb', line 408

def authenticate_jwt_local(session_jwt, max_token_age_seconds: nil, authorization_check: nil)
  max_token_age_seconds = 300 if max_token_age_seconds.nil?

  issuer = 'stytch.com/' + @project_id
  begin
    decoded_token = JWT.decode session_jwt, nil, true,
                               { jwks: @jwks_loader, iss: issuer, verify_iss: true, aud: @project_id, verify_aud: true, algorithms: ['RS256'] }

    session = decoded_token[0]
    iat_time = Time.at(session['iat']).to_datetime
    return nil unless iat_time + max_token_age_seconds >= Time.now

    session = marshal_jwt_into_session(session)
  rescue JWT::InvalidIssuerError
    raise Stytch::JWTInvalidIssuerError
  rescue JWT::InvalidAudError
    raise Stytch::JWTInvalidAudienceError
  rescue JWT::ExpiredSignature
    raise Stytch::JWTExpiredSignatureError
  rescue JWT::IncorrectAlgorithm
    raise Stytch::JWTIncorrectAlgorithmError
  end

  # Do the auth check - intentionally don't rescue errors from here
  if authorization_check && session['roles']
    @policy_cache.perform_authorization_check(
      subject_roles: session['roles'],
      subject_org_id: session['member_session']['organization_id'],
      authorization_check: authorization_check
    )
  end

  session
end

#exchange(organization_id:, session_token: nil, session_jwt: nil, session_duration_minutes: nil, session_custom_claims: nil, locale: nil) ⇒ Object

Use this endpoint to exchange a Member’s existing session for another session in a different Organization. This can be used to accept an invite, but not to create a new member via domain matching.

To create a new member via domain matching, use the [Exchange Intermediate Session](stytch.com/docs/b2b/api/exchange-intermediate-session) flow instead.

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. Any OAuth Tokens owned by the Member will not be transferred to the new Organization. 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.

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. The `intermediate_session_token` can be passed into the [OTP SMS Authenticate endpoint](stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the MFA step and acquire a full member session. The `intermediate_session_token` can also be used with the [Exchange Intermediate Session endpoint](stytch.com/docs/b2b/api/exchange-intermediate-session) or the [Create Organization via Discovery endpoint](stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. The `session_duration_minutes` and `session_custom_claims` parameters will be ignored.

Parameters:

organization_id

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. The type of this field is String.

session_token

The ‘session_token` belonging to the member that you wish to associate the email with. The type of this field is nilable String.

session_jwt

The ‘session_jwt` belonging to the member that you wish to associate the email with. The type of this field is nilable String.

session_duration_minutes

Set the session lifetime to be this many minutes from now. This will start a new session if one doesn’t already exist, returning both an opaque ‘session_token` and `session_jwt` for this session. Remember that the `session_jwt` will have a fixed lifetime of five minutes regardless of the underlying session duration, and will need to be refreshed over time.

This value must be a minimum of 5 and a maximum of 527040 minutes (366 days).

If a ‘session_token` or `session_jwt` is provided then a successful authentication will continue to extend the session this many minutes.

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 to use the Stytch session product, you can ignore the session fields in the response. The type of this field is nilable Integer.

session_custom_claims

Add a custom claims map to the Session being authenticated. Claims are only created if a Session is initialized by providing a value in ‘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 delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored. Total custom claims size cannot exceed four kilobytes. The type of this field is nilable object.

locale

If the Member 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.

Parameter is a [IETF BCP 47 language tag](www.w3.org/International/articles/language-tags/), e.g. ‘“en”`.

Currently supported languages are English (‘“en”`), Spanish (`“es”`), and Brazilian Portuguese (`“pt-br”`); if no value is provided, the copy defaults to English.

Request support for additional languages [here](docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link“)!

The type of this field is nilable +ExchangeRequestLocale+ (string enum).

Returns:

An object with the following fields:

request_id

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. The type of this field is String.

member_id

Globally unique UUID that identifies a specific Member. The type of this field is String.

member_session

The [Session object](stytch.com/docs/b2b/api/session-object). The type of this field is MemberSession (object).

session_token

A secret token for a given Stytch Session. The type of this field is String.

session_jwt

The JSON Web Token (JWT) for a given Stytch Session. The type of this field is String.

member

The [Member object](stytch.com/docs/b2b/api/member-object) The type of this field is Member (object).

organization

The [Organization object](stytch.com/docs/b2b/api/organization-object). The type of this field is Organization (object).

member_authenticated

Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step to log in to the Organization. The type of this field is Boolean.

intermediate_session_token

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](stytch.com/docs/b2b/api/authenticate-otp-sms), [TOTP Authenticate endpoint](stytch.com/docs/b2b/api/authenticate-totp), or [Recovery Codes Recover endpoint](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](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](stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. The type of this field is String.

status_code

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. The type of this field is Integer.

mfa_required

Information about the MFA requirements of the Organization and the Member’s options for fulfilling MFA. The type of this field is nilable MfaRequired (object).

primary_required

(no documentation yet) The type of this field is nilable PrimaryRequired (object).



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/stytch/b2b_sessions.rb', line 298

def exchange(
  organization_id:,
  session_token: nil,
  session_jwt: nil,
  session_duration_minutes: nil,
  session_custom_claims: nil,
  locale: nil
)
  headers = {}
  request = {
    organization_id: organization_id
  }
  request[:session_token] = session_token unless session_token.nil?
  request[:session_jwt] = session_jwt unless session_jwt.nil?
  request[:session_duration_minutes] = session_duration_minutes unless session_duration_minutes.nil?
  request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
  request[:locale] = locale unless locale.nil?

  post_request('/v1/b2b/sessions/exchange', request, headers)
end

#get(organization_id:, member_id:) ⇒ Object

Retrieves all active Sessions for a Member.

Parameters:

organization_id

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. The type of this field is String.

member_id

Globally unique UUID that identifies a specific Member. The ‘member_id` is critical to perform operations on a Member, so be sure to preserve this value. The type of this field is String.

Returns:

An object with the following fields:

request_id

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. The type of this field is String.

member_sessions

An array of [Session objects](stytch.com/docs/b2b/api/session-object). The type of this field is list of MemberSession (object).

status_code

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. The type of this field is Integer.



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/stytch/b2b_sessions.rb', line 58

def get(
  organization_id:,
  member_id:
)
  headers = {}
  query_params = {
    organization_id: organization_id,
    member_id: member_id
  }
  request = request_with_query_params('/v1/b2b/sessions', query_params)
  get_request(request, headers)
end

#get_jwks(project_id:) ⇒ Object

Get the JSON Web Key Set (JWKS) for a project.

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.

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.

If you’re using one of our [backend SDKs](stytch.com/docs/b2b/sdks), the JWKS roll will be handled for you.

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.

Parameters:

project_id

The ‘project_id` to get the JWKS for. The type of this field is String.

Returns:

An object with the following fields:

keys

The JWK The type of this field is list of JWK (object).

request_id

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. The type of this field is String.

status_code

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. The type of this field is Integer.



345
346
347
348
349
350
351
352
# File 'lib/stytch/b2b_sessions.rb', line 345

def get_jwks(
  project_id:
)
  headers = {}
  query_params = {}
  request = request_with_query_params("/v1/b2b/sessions/jwks/#{project_id}", query_params)
  get_request(request, headers)
end

#marshal_jwt_into_session(jwt) ⇒ Object

Note that the ‘user_id’ field is DEPRECATED: Use member_id instead This field will be removed in a future MAJOR release.



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/stytch/b2b_sessions.rb', line 445

def marshal_jwt_into_session(jwt)
  stytch_claim = 'https://stytch.com/session'
  organization_claim = 'https://stytch.com/organization'

  expires_at = jwt[stytch_claim]['expires_at'] || Time.at(jwt['exp']).to_datetime.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
  # The custom claim set is all the claims in the payload except for the standard claims and
  # the Stytch session claim. The cleanest way to collect those seems to be naming what we want
  # to omit and filtering the rest to collect the custom claims.
  reserved_claims = ['aud', 'exp', 'iat', 'iss', 'jti', 'nbf', 'sub', stytch_claim, organization_claim]
  custom_claims = jwt.reject { |key, _| reserved_claims.include?(key) }
  {
    'member_session' => {
      'session_id' => jwt[stytch_claim]['id'],
      'organization_id' => jwt[organization_claim]['organization_id'],
      'member_id' => jwt['sub'],
      # DEPRECATED: Use member_id instead
      'user_id' => jwt['sub'],
      'started_at' => jwt[stytch_claim]['started_at'],
      'last_accessed_at' => jwt[stytch_claim]['last_accessed_at'],
      # For JWTs that include it, prefer the inner expires_at claim.
      'expires_at' => expires_at,
      'attributes' => jwt[stytch_claim]['attributes'],
      'authentication_factors' => jwt[stytch_claim]['authentication_factors'],
      'custom_claims' => custom_claims
    },
    'roles' => jwt[stytch_claim]['roles']
  }
end

#revoke(member_session_id: nil, session_token: nil, session_jwt: nil, member_id: nil) ⇒ Object

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`.

Parameters:

member_session_id

Globally unique UUID that identifies a specific Session in the Stytch API. The ‘member_session_id` is critical to perform operations on an Session, so be sure to preserve this value. The type of this field is nilable String.

session_token

A secret token for a given Stytch Session. The type of this field is nilable String.

session_jwt

The JSON Web Token (JWT) for a given Stytch Session. The type of this field is nilable String.

member_id

Globally unique UUID that identifies a specific Member. The ‘member_id` is critical to perform operations on a Member, so be sure to preserve this value. The type of this field is nilable String.

Returns:

An object with the following fields:

request_id

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. The type of this field is String.

status_code

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. The type of this field is Integer.



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/stytch/b2b_sessions.rb', line 192

def revoke(
  member_session_id: nil,
  session_token: nil,
  session_jwt: nil,
  member_id: nil
)
  headers = {}
  request = {}
  request[:member_session_id] = member_session_id unless member_session_id.nil?
  request[:session_token] = session_token unless session_token.nil?
  request[:session_jwt] = session_jwt unless session_jwt.nil?
  request[:member_id] = member_id unless member_id.nil?

  post_request('/v1/b2b/sessions/revoke', request, headers)
end