Class: StytchB2B::Sessions

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

Defined Under Namespace

Classes: RevokeRequestOptions

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, jwks_cache, policy_cache) ⇒ Sessions

Returns a new instance of Sessions.



37
38
39
40
41
42
43
# File 'lib/stytch/b2b_sessions.rb', line 37

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

  @policy_cache = policy_cache
  @project_id = project_id
  @jwks_cache = jwks_cache
end

Instance Method Details

#attest(profile_id:, token:, organization_id: nil, session_duration_minutes: nil, session_custom_claims: nil, session_token: nil, session_jwt: nil, telemetry_id: nil) ⇒ Object

Exchange an auth token issued by a trusted identity provider for a Stytch session. You must first register a Trusted Auth Token profile in the Stytch dashboard [here](stytch.com/dashboard/trusted-auth-tokens). If a session token or session JWT is provided, it will add the trusted auth token as an authentication factor to the existing session.

Parameters:

profile_id

The ID of the trusted auth token profile to use for attestation. The type of this field is String.

token

The trusted auth token to authenticate. The token must have an organization ID claim if JIT provisioning is enabled. The type of this field is String.

organization_id

The organization ID that the session should be authenticated in. Must be provided if the trusted auth token does not have an organization ID claim. 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.

session_token

The ‘session_token` for the session that you wish to add the trusted auth token authentication factor to. The type of this field is nilable String.

session_jwt

The ‘session_jwt` for the session that you wish to add the trusted auth token authentication factor to. The type of this field is nilable String.

telemetry_id

If the ‘telemetry_id` is passed, as part of this request, Stytch will call the [Fingerprint Lookup API](stytch.com/docs/fraud/api/fingerprint-lookup) and store the associated fingerprints and IPGEO information for the Member. Your workspace must be enabled for Device Fingerprinting to use this feature. 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.

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

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.

member_device

If a valid ‘telemetry_id` was passed in the request and the [Fingerprint Lookup API](stytch.com/docs/fraud/api/fingerprint-lookup) returned results, the `member_device` response field will contain information about the member’s device attributes. The type of this field is nilable DeviceInfo (object).



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/stytch/b2b_sessions.rb', line 492

def attest(
  profile_id:,
  token:,
  organization_id: nil,
  session_duration_minutes: nil,
  session_custom_claims: nil,
  session_token: nil,
  session_jwt: nil,
  telemetry_id: nil
)
  headers = {}
  request = {
    profile_id: profile_id,
    token: token
  }
  request[:organization_id] = organization_id unless organization_id.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[:session_token] = session_token unless session_token.nil?
  request[:session_jwt] = session_jwt unless session_jwt.nil?
  request[:telemetry_id] = telemetry_id unless telemetry_id.nil?

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

#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. See our [How to use Stytch Session JWTs](stytch.com/docs/b2b/guides/sessions/resources/using-jwts) guide for more information.

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 information about why the Member was granted permission. The type of this field is nilable AuthorizationVerdict (object).



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/stytch/b2b_sessions.rb', line 158

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, clock_tolerance_seconds: 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. If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
# File 'lib/stytch/b2b_sessions.rb', line 641

def authenticate_jwt(
  session_jwt,
  max_token_age_seconds: nil,
  session_duration_minutes: nil,
  session_custom_claims: nil,
  authorization_check: nil,
  clock_tolerance_seconds: nil
)
  max_token_age_seconds = 300 if max_token_age_seconds.nil?
  clock_tolerance_seconds = 0 if clock_tolerance_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, clock_tolerance_seconds: clock_tolerance_seconds)
  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, clock_tolerance_seconds: 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. If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/stytch/b2b_sessions.rb', line 686

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

  default_issuer = 'stytch.com/' + @project_id
  base_url_issuer = @connection.url_prefix
  valid_issuers = [default_issuer, base_url_issuer]

  begin
    decoded_token = JWT.decode session_jwt, nil, true,
                               { jwks: @jwks_cache.loader, iss: valid_issuers, verify_iss: true, aud: @project_id, verify_aud: true, algorithms: ['RS256'], nbf_leeway: clock_tolerance_seconds }

    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, telemetry_id: 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 email domain JIT Provisioning, use the [Exchange Intermediate Session](stytch.com/docs/b2b/api/exchange-intermediate-session) flow instead.

If the user has already satisfied the authentication requirements of the Organization they are trying to switch into, this API will return ‘member_authenticated: true` and a `session_token` and `session_jwt`.

If the user **has not** satisfied the primary or secondary authentication requirements of the Organization they are attempting to switch into, this API will return ‘member_authenticated: false` and an `intermediate_session_token`.

If ‘primary_required` is set, prompt the user to fulfill the Organization’s auth requirements using the options returned in ‘primary_required.allowed_auth_methods`.

If ‘primary_required` is null and `mfa_required` is set, check `mfa_required.member_options` to determine if the Member has SMS OTP or TOTP set up for MFA and prompt accordingly. If the Member has SMS OTP, check `mfa_required.secondary_auth_initiated` to see if the OTP has already been sent.

Include the ‘intermediate_session_token` returned above when calling the `authenticate()` method that the user needed to perform. Once the user has completed the authentication requirements they were missing, they will be granted a full `session_token` and `session_jwt` to indicate they have successfully logged into the Organization.

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. You may also use the organization_slug or organization_external_id here as a convenience. 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 an [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).
telemetry_id

If the ‘telemetry_id` is passed, as part of this request, Stytch will call the [Fingerprint Lookup API](stytch.com/docs/fraud/api/fingerprint-lookup) and store the associated fingerprints and IPGEO information for the Member. Your workspace must be enabled for Device Fingerprinting to use this feature. 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.

member_id

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

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. The token has a default expiry of 10 minutes. 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. Intermediate Session Tokens have a default expiry of 10 minutes. 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.

member_session

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

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

Information about the primary authentication requirements of the Organization. The type of this field is nilable PrimaryRequired (object).

member_device

If a valid ‘telemetry_id` was passed in the request and the [Fingerprint Lookup API](stytch.com/docs/fraud/api/fingerprint-lookup) returned results, the `member_device` response field will contain information about the member’s device attributes. The type of this field is nilable DeviceInfo (object).



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/stytch/b2b_sessions.rb', line 321

def exchange(
  organization_id:,
  session_token: nil,
  session_jwt: nil,
  session_duration_minutes: nil,
  session_custom_claims: nil,
  locale: nil,
  telemetry_id: 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?
  request[:telemetry_id] = telemetry_id unless telemetry_id.nil?

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

#exchange_access_token(access_token:, session_duration_minutes: nil, session_custom_claims: nil, telemetry_id: nil) ⇒ Object

Use this endpoint to exchange a Connected Apps Access Token back into a Member Session for the underlying Member. This session can be used with the Stytch SDKs and APIs.

The Access Token must contain the ‘full_access` scope (only available to First Party clients) and must not be more than 5 minutes old. Access Tokens may only be exchanged a single time.

Because the Member previously completed MFA and satisfied all Organization authentication requirements at the time of the original Access Token issuance, this endpoint will never return an ‘intermediate_session_token` or require MFA.

Parameters:

access_token

The access token to exchange for a Stytch Session. Must be granted the ‘full_access` scope. The type of this field is 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.

telemetry_id

If the ‘telemetry_id` is passed, as part of this request, Stytch will call the [Fingerprint Lookup API](stytch.com/docs/fraud/api/fingerprint-lookup) and store the associated fingerprints and IPGEO information for the Member. Your workspace must be enabled for Device Fingerprinting to use this feature. 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.

member_id

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

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.

member_session

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

member_device

If a valid ‘telemetry_id` was passed in the request and the [Fingerprint Lookup API](stytch.com/docs/fraud/api/fingerprint-lookup) returned results, the `member_device` response field will contain information about the member’s device attributes. The type of this field is nilable DeviceInfo (object).



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/stytch/b2b_sessions.rb', line 406

def exchange_access_token(
  access_token:,
  session_duration_minutes: nil,
  session_custom_claims: nil,
  telemetry_id: nil
)
  headers = {}
  request = {
    access_token: access_token
  }
  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[:telemetry_id] = telemetry_id unless telemetry_id.nil?

  post_request('/v1/b2b/sessions/exchange_access_token', 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. You may also use the organization_slug or organization_external_id here as a convenience. 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. You may use an external_id here if one is set for the member. 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.



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/stytch/b2b_sessions.rb', line 66

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.

Within the JWKS, the JSON Web Keys are rotated every ~6 months. Upon rotation, new JWTs will be signed using the new key, and both keys 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 keys, and some JWTs will be signed by the new keys. The correct key to use for validation is determined by matching the ‘kid` value of the JWT and key.

If you’re using one of our [backend SDKs](stytch.com/docs/b2b/sdks), the JSON Web Key (JWK) rotation will be handled for you.

If you’re using your own JWT validation library, many have built-in support for JWK rotation, and you’ll just need to supply this API endpoint. If not, your application should decide which JWK to use for validation by inspecting the ‘kid` value.

See our [How to use Stytch Session JWTs](stytch.com/docs/b2b/guides/sessions/resources/using-jwts) guide for more information.

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 list of JWKs associated with the project. 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.



619
620
621
622
623
624
625
626
# File 'lib/stytch/b2b_sessions.rb', line 619

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.



727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/stytch/b2b_sessions.rb', line 727

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

#migrate(session_token:, organization_id:, session_duration_minutes: nil, session_custom_claims: nil) ⇒ Object

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](stytch.com/dashboard/migrations), 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 Member in your Organization and create a Stytch Session. You will need to create the member before using this endpoint.

Parameters:

session_token

The authorization token Stytch will pass in to the external userinfo endpoint. The type of this field is String.

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. You may also use the organization_slug or organization_external_id here as a convenience. The type of this field is 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.

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.

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

(no documentation yet) The type of this field is Integer.

member_session

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



574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/stytch/b2b_sessions.rb', line 574

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

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

#revoke(member_session_id: nil, session_token: nil, session_jwt: nil, member_id: nil, method_options: 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.

Method Options:

This method supports an optional StytchB2B::Sessions::RevokeRequestOptions object which will modify the headers sent in the HTTP request.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/stytch/b2b_sessions.rb', line 203

def revoke(
  member_session_id: nil,
  session_token: nil,
  session_jwt: nil,
  member_id: nil,
  method_options: nil
)
  headers = {}
  headers = headers.merge(method_options.to_headers) unless method_options.nil?
  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