class StytchB2B::Sessions
def authenticate(
the complete list of Roles that gave the Member permission to perform the specified action on the specified Resource.
If an `authorization_check` is provided in the request and the check succeeds, this field will return
verdict::
The type of this field is +Integer+.
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.
status_code::
The type of this field is +Organization+ (+object+).
The [Organization object](https://stytch.com/docs/b2b/api/organization-object).
organization::
The type of this field is +Member+ (+object+).
The [Member object](https://stytch.com/docs/b2b/api/member-object)
member::
The type of this field is +String+.
The JSON Web Token (JWT) for a given Stytch Session.
session_jwt::
The type of this field is +String+.
A secret token for a given Stytch Session.
session_token::
The type of this field is +MemberSession+ (+object+).
The [Session object](https://stytch.com/docs/b2b/api/session-object).
member_session::
The type of this field is +String+.
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.
request_id::
An object with the following fields:
== Returns:
The type of this field is nilable +AuthorizationCheck+ (+object+).
Otherwise, the response will contain a list of Roles that satisfied the authorization check.
`organization_id` does not match the Member's Organization, a 403 error will be thrown.
If the Member is not authorized to perform the specified action on the specified Resource, or if the
factor on the Member Session from the specified SSO connection.
assigned by SSO connection or SSO group will only be valid for a Member Session if there is at least one authentication
The Roles on the Member Session may differ from the Roles you see on the Member object - Roles that are implicitly
In addition, the `organization_id` passed in the authorization check must match the Member's Organization.
[explicitly or implicitly](https://stytch.com/docs/b2b/guides/rbac/role-assignment), with adequate permissions.
their Member Session contains a Role, assigned
authorized to perform the given action on the given Resource in the specified Organization. A Member is authorized if
If an `authorization_check` object is passed in, this endpoint will also check if the Member is
authorization_check::
The type of this field is nilable +object+.
Total custom claims size cannot exceed four kilobytes.
delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored.
`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
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_custom_claims::
The type of this field is nilable +String+.
The JSON Web Token (JWT) for a given Stytch Session.
session_jwt::
The type of this field is nilable +Integer+.
to use the Stytch session product, you can ignore the session fields in the response.
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
If a `session_token` or `session_jwt` is provided then a successful authentication will continue to extend the session this many minutes.
This value must be a minimum of 5 and a maximum of 527040 minutes (366 days).
five minutes regardless of the underlying session duration, and will need to be refreshed over time.
returning both an opaque `session_token` and `session_jwt` for this session. Remember that the `session_jwt` will have a fixed lifetime of
Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't already exist,
session_duration_minutes::
The type of this field is nilable +String+.
A secret token for a given Stytch Session.
session_token::
== Parameters:
Otherwise, the response will contain a list of Roles that satisfied the authorization check.
`organization_id` does not match the Member's Organization, a 403 error will be thrown.
If the Member is not authorized to perform the specified action on the specified Resource, or if the
In addition, the `organization_id` passed in the authorization check must match the Member's Organization.
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](https://stytch.com/docs/b2b/guides/rbac/role-assignment), with adequate permissions.
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.
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.
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
def authenticate_jwt(
This field will be removed in a future MAJOR release.
Note that the 'user_id' field of the returned session is DEPRECATED: Use member_id instead
To force remote validation for all tokens, set max_token_age_seconds to 0 or call authenticate()
max_token_age_seconds seconds ago, then just verify locally and don't call the API
If max_token_age_seconds is set and the JWT was issued (based on the "iat" claim) less than
Parse a JWT and verify the signature. If max_token_age_seconds is unset, call the API directly
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
def authenticate_jwt_local(session_jwt, max_token_age_seconds: nil, authorization_check: nil)
This method never authenticates a JWT directly with the API
function to get the JWK
Uses the cached value to get the JWK but if it is unavailable, it calls the get_jwks()
Parse a JWT and verify the signature locally (without calling /authenticate in the API)
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
def exchange(
Information about the MFA requirements of the Organization and the Member's options for fulfilling MFA.
mfa_required::
The type of this field is +Integer+.
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.
status_code::
The type of this field is +String+.
or the [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization.
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,
or [Recovery Codes Recover endpoint](https://stytch.com/docs/b2b/api/recovery-codes-recover) to complete the MFA flow and log in to the target 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),
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.
intermediate_session_token::
The type of this field is +Boolean+.
Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step to log in to the Organization.
member_authenticated::
The type of this field is +Organization+ (+object+).
The [Organization object](https://stytch.com/docs/b2b/api/organization-object).
organization::
The type of this field is +Member+ (+object+).
The [Member object](https://stytch.com/docs/b2b/api/member-object)
member::
The type of this field is +String+.
The JSON Web Token (JWT) for a given Stytch Session.
session_jwt::
The type of this field is +String+.
A secret token for a given Stytch Session.
session_token::
The type of this field is +MemberSession+ (+object+).
The [Session object](https://stytch.com/docs/b2b/api/session-object).
member_session::
The type of this field is +String+.
Globally unique UUID that identifies a specific Member.
member_id::
The type of this field is +String+.
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.
request_id::
An object with the following fields:
== Returns:
The type of this field is nilable +ExchangeRequestLocale+ (string enum).
Request support for additional languages [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")!
Currently supported languages are English (`"en"`), Spanish (`"es"`), and Brazilian Portuguese (`"pt-br"`); if no value is provided, the copy defaults to English.
Parameter is a [IETF BCP 47 language tag](https://www.w3.org/International/articles/language-tags/), e.g. `"en"`.
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.
locale::
The type of this field is nilable +object+.
Total custom claims size cannot exceed four kilobytes.
delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored.
`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
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_custom_claims::
The type of this field is nilable +Integer+.
to use the Stytch session product, you can ignore the session fields in the response.
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
If a `session_token` or `session_jwt` is provided then a successful authentication will continue to extend the session this many minutes.
This value must be a minimum of 5 and a maximum of 527040 minutes (366 days).
five minutes regardless of the underlying session duration, and will need to be refreshed over time.
returning both an opaque `session_token` and `session_jwt` for this session. Remember that the `session_jwt` will have a fixed lifetime of
Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't already exist,
session_duration_minutes::
The type of this field is nilable +String+.
The `session_jwt` belonging to the member that you wish to associate the email with.
session_jwt::
The type of this field is nilable +String+.
The `session_token` belonging to the member that you wish to associate the email with.
session_token::
The type of this field is +String+.
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.
organization_id::
== Parameters:
The `session_duration_minutes` and `session_custom_claims` parameters will be ignored.
The `intermediate_session_token` can also be used with the [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) or the [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one.
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.
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.
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.
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.
To create a new member via domain matching, use the [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) flow instead.
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.
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
def get(
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.
status_code::
The type of this field is list of +MemberSession+ (+object+).
An array of [Session objects](https://stytch.com/docs/b2b/api/session-object).
member_sessions::
The type of this field is +String+.
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.
request_id::
An object with the following fields:
== Returns:
The type of this field is +String+.
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.
member_id::
The type of this field is +String+.
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.
organization_id::
== Parameters:
Retrieves all active Sessions for a Member.
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
def get_jwks(
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.
status_code::
The type of this field is +String+.
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.
request_id::
The type of this field is list of +JWK+ (+object+).
The JWK
keys::
An object with the following fields:
== Returns:
The type of this field is +String+.
The `project_id` to get the JWKS for.
project_id::
== Parameters:
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.
If you're using one of our [backend SDKs](https://stytch.com/docs/b2b/sdks), the JWKS roll will be handled for you.
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.
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.
Get the JSON Web Key Set (JWKS) for a project.
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
def initialize(connection, project_id, policy_cache)
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
def marshal_jwt_into_session(jwt)
Note that the 'user_id' field is DEPRECATED: Use member_id instead
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
def revoke(
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.
status_code::
The type of this field is +String+.
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.
request_id::
An object with the following fields:
== Returns:
The type of this field is nilable +String+.
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.
member_id::
The type of this field is nilable +String+.
The JSON Web Token (JWT) for a given Stytch Session.
session_jwt::
The type of this field is nilable +String+.
A secret token for a given Stytch Session.
session_token::
The type of this field is nilable +String+.
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.
member_session_id::
== Parameters:
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`.
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