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 90 days long (129600 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 a map where the keys are strings, and the values can be of any type. Custom claims are persisted on the session object and encoded in the JWT.

To update a key in an existing section, supply a new value.

// current claims object {“key_1”: 1, “key_2”: 2}
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}
sessions.authenticate(token, custom_claims={“key_1”: null})
// resulting claims object {“key_2”: 2}

Values using reserved claims (“iss", “sub”, “aud”, “exp”, “nbf”, “iat”, “jti”) will be ignored. Total custom claims size cannot exceed four bytes. If a value for one of your custom claims is itself a map, you can update and delete values in the same way.

Request: sessions.authenticate(token, custom_claims={"b": null, "c": 3.5, "e": {"nested1": "val1", "nested2": "val2"}})
Response: session.custom_claims = {"c": 3.5, "d": 4, "e": {"nested1": "val1", "nested2": "val2"}}
Request: sessions.authenticate(token, custom_claims={"e": {"nested1": nil, "nested3": "val3"})
Response: session.custom_claims = {"c": 3.5, "d": 4, "e": {"nested2": "val2", "nested3": "val3"}}


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 client libraries (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.