Sessions overview

Stytch user sessions are identified by a session token that should be stored client-side (usually a browser cookie) and authenticated on each request.


How to use sessions

Stytch user sessions are identified by a session token that should be stored client-side (usually a browser cookie) and authenticated on each request. To start a session, use the authenticate magic link or authenticate OTP endpoint as usual and add the session_duration_minutes parameter to set the lifetime of the session. The responses of these endpoints will include a session_token and session_jwt that you can forward to the client and store. Before performing any action that requires authorization, call authenticate session to ensure that the session is still valid.


Beginning a session

When handling the token for a new authentication factor (authenticate magic link and authenticate OTP), include a session_duration_minutes field to begin a new session. Sessions can be between 5 minutes and 366 days long (527040 minutes). If you provide this field, the authenticate method’s response field will include values for session, session_token, and session_jwt.

Authenticating a session

On each request, before doing anything that requires authorization, call authenticate session to ensure that the session is valid. If it is, use the user_id value to identify the user and send the session_token value to the user in a session cookie. If it isn’t valid, clear the session cookie to log the user out and do not process the request. sessions.authenticate always returns the session token for convenience. We recommend following OWASP's guide on cookie storage.

Extending or revoking a session

To extend a session’s lifetime, call authenticate session with the session_duration_minutes parameter. The session will be set to expire that many minutes from now. This will still return the original session token even though its lifetime was extended. To revoke a session, call revoke session with the session ID or session token (whichever is more convenient). We recommend showing the user a list of all their active sessions so they can revoke any they don’t recognize by IP address and/or User-Agent. To attach those values to sessions, add them to the attributes parameter in calls to authenticate magic link or authenticate OTP.

Session management examples

Below are examples of ways to use session management

  1. Remember me for 30 days after login

    Create a session that expires 30 days (43200 minutes) after initial login

    curl --request POST \
    	--url https://test.stytch.com/v1/magic_links/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
    		"session_duration_minutes": 43200
    	}'
    
    curl --request POST \
    	--url https://test.stytch.com/sessions/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q"
    	}'
  2. Remember me for 30 days since you last saw me

    Everytime a session is authenticated, extend it for another 30 days (43200 minutes). This means that if the session continues to be successfully authenticated at least once every 30 days the user will remain logged in indefinitely, unless the session is explicitly revoked.

    curl --request POST \
    	--url https://test.stytch.com/v1/magic_links/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
    		"session_duration_minutes": 43200
    	}'
    
    curl --request POST \
    	--url https://test.stytch.com/sessions/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
    		"session_duration_minutes": 43200
    	}'
  3. Log out a user

    Log the user out of a given session

    curl --request POST \
    	--url https://test.stytch.com/v1/sessions/revoke \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"session_id": "session-test-fe6c042b-6286-479f-8a4f-b046a6c46509"
    	}'
  4. Log a user out of all sessions

    Get all sessions for a given user's ID and individually revoke each of them.

    curl --request GET \
    	--url https://test.stytch.com/v1/sessions?user_id=user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6 \
    	-u 'PROJECT_ID:SECRET'
    
    curl --request POST \
    	--url https://test.stytch.com/v1/sessions/revoke \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"session_id": "session-test-fe6c042b-6286-479f-8a4f-b046a6c46509"
    	}'
  5. Multiple Authentication Factors

    Create a single session from multiple authentication factors.

    # Create a new session using the first factor
    curl --request POST \
    	--url https://test.stytch.com/v1/magic_links/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=",
    		"session_duration_minutes": 43200
    	}'
    
    # Use the session token to attach the second factor
    curl --request POST \
    	--url https://test.stytch.com/v1/otps/authenticate \
    	-u 'PROJECT_ID:SECRET' \
    	-H 'Content-Type: application/json' \
    	-d '{
    		"method_id": "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0",
    		"code": "123456",
    		"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q"
    	}'

Adding custom claims to sessions

You can add custom claims to a Stytch session by including the session_custom_claims argument on any authenticate method. This argument takes in an arbitrary JSON object - which may be represented as a map, dictionary, or object depending on your language of choice. Custom claims are persisted on the session object and encoded in the session JWT.

To add or update a key, supply a new value.

# initial claims object {}
stytch.sessions.authenticate(token, custom_claims={"key_1": 1, "key_2": 2})
# current claims object {"key_1": 1, "key_2": 2}
stytch.sessions.authenticate(token, custom_claims={"key_1": 9})
# resulting claims object {"key_1": 9, "key_2": 2}

To delete a key, supply a null value.

# current claims object {"key_1": 1, "key_2": 2}
stytch.sessions.authenticate(token, custom_claims={"key_1": 9})
# resulting claims object {"key_2": 2}

If a value for one of your custom claims is itself a JSON object, you can update and delete values in the same way.

sessions.authenticate(token, custom_claims={ 
    "b": null, 
    "c": 3.5, 
    "e": {
        "nested1": "val1", 
        "nested2": "val2"
    }
})
# resulting claims object  
# {
#    "c": 3.5,
#    "d": 4,
#    "e": {
#        "nested1": "val1",
#        "nested2": "val2"
#    }
# }

stytch.sessions.authenticate(token, custom_claims={
    "e": {
        "nested1": nil, 
        "nested3": "val3"
    }
)
# resulting claims object  
# {
#     "c": 3.5, 
#     "d": 4, 
#     "e": {
#         "nested2": "val2", 
#         "nested3": "val3"
#     }
# }

Limitations

  • Certain claims are reserved and will result in an error if they are set (iss, sub, aud, exp, nbf, iat, jti, https://stytch.com/*)
  • Total custom claims size cannot exceed four kilobytes.

Custom Claim templates

If you want to add the same set of custom claims to every session for your project, Custom Claim Templates may be a good fit.

Custom Claim Templates can be used to:

  • Pass RBAC information from User Metadata to Sessions.
  • Integrate with third-party providers that support JWT-based authentication, such as Hasura.

Custom Claim Template Overview

Custom Claim Templates use a markup language to generate a JSON object using the user's information.

  • The JSON object output for a particular user will be used as the initial set of custom claims for all of that user's sessions.
  • Claims from templates can still be updated, deleted, or added to by passing in a session_custom_claims argument in an API request.
  • Claims from Custom Claim Templates are subject to the same set of limitations that API-driven custom claims have: the total size cannot exceed 4kb, and no registered claims may be used to ensure interoperability.
  • Updates to the Custom Claim Template or User Metadata will propagate to existing sessions the next time a JWT is minted. Previously minted JWTs are immutable and cannot be updated. Clients can force a new JWT to be minted by calling the Authenticate Session endpoint.

Custom Claim Template Markup Syntax

The Custom Claim Template markup language uses {{ variable }} syntax to denote information that should be passed in at runtime. When dealing with User Metadata, use dot notation to access nested fields, e.g. {{ user.trusted_metadata.subscription.level }} will access the level field of the subscription object in trusted_metadata on a Stytch User object.

Variables can evaluate to any JSON object - strings, numbers, null, objects, or arrays. Variables can only be used as JSON values, and cannot be used as object keys.

If a variable evaluates to null, or attempts to access a value that does not exist, the generated claim will not be present in the output.

Today, the following template variables are supported:

  • {{ user.user_id }}
  • {{ user.full_name }}
  • {{ user.trusted_metadata.$PATH }}

More variables will be added in the future.

Example

For example, the template:

{
  "https://hasura.io/jwt/claims": {
    "x-hasura-default-role": "reader",
    "x-hasura-allowed-roles": {{ user.trusted_metadata.roles }},
    "x-hasura-user-id": {{ user.user_id }}
  }
}

could be combined with the user information:

{
  "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
  "trusted_metadata": {
    "roles": ["admin", "reader"]
  }
}

to produce the final set of custom claims:

{
  "https://hasura.io/jwt/claims": {
    "x-hasura-default-role": "reader",
    "x-hasura-allowed-roles": ["admin", "reader"],
    "x-hasura-user-id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6"
  }
}

Any feedback? We'd love to hear it! Reach out to support@stytch.com.


Session tokens vs JWTs

Stytch user sessions are identified by a session token (session_token) or session JWT (session_jwt) that should be stored client-side (usually a browser cookie) and authenticated on each request. During each successful session creation or authentication, both a token and a JWT are returned in the API response.

The session token is a unique and opaque 44-character string, while the session JWT is a string that follows standard JWT protocols. The session token and the session JWT are completely interoperable, and both are returned on every API response so that developers can use whichever is best for their application.

For more information, please check out our blog post on the same topic.


Session tokens

  • These are considered opaque because they don't contain any information about the user or the underlying session
  • Session tokens need to be authenticated via the SessionsAuthenticate endpoint before a user takes any action that requires authentication
  • The session token will not authenticate and will be considered invalid if underlying session is revoked
You might use session tokens if...
  • Your security needs require that your app must never accidentally use a revoked session (i.e. even the small 5 minute grace period of our default JWTs is not acceptable to your app's security)
  • Your access to user-side storage is limited and can only store small values
  • You don't want to expose the session data (authentication factors) or metadata (timestamps) in user storage


JWTs

  • Contains standard claims as well as information about the Stytch session
  • Session JWTs can be authenticated locally without an API call. A session JWT is signed by project-specific keys stored by Stytch. You can retrieve your project's public keyset via our GetJWKS endpoint
  • Expires after 5 minutes but can be refreshed via our SessionsAuthenticate endpoint for the duration of the underlying Stytch session
  • The session JWT will successfully locally validate until the five minute expiration mark, even if the underlying session is revoked. You can always refresh more frequently than that if you prefer
You might use JWTs if...
  • Your application would benefit from the performance improvements of validating user sessions without an external network request
  • You're using Stytch sessions to authorize actions outside of your app and that authorization works via JWT
We strongly recommend that you use our Backend SDKs (available in Node, Python, Ruby, and Go) if you are using JWTs. Our libraries handle the logic to authenticate JWTs locally and automatically fall back to the Stytch API when the JWT is expired.