Adding custom claims to sessions
Custom claims allow you to encode additional information into your Stytch session JWTs. 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.
Use cases
Custom claims can be used to:
- Pass user-specific information to your application
- Integrate with third-party services that expect specific JWT claims
- Store temporary session state or user preferences
- Implement custom authorization logic
How to use
Adding or updating claims
To add or update a key, supply a new value:
# initial claims object {}
stytch.sessions.authenticate(token, session_custom_claims={"key_1": 1, "key_2": 2})
# current claims object {"key_1": 1, "key_2": 2}
stytch.sessions.authenticate(token, session_custom_claims={"key_1": 9})
# resulting claims object {"key_1": 9, "key_2": 2}
Deleting claims
To delete a key, supply a null value:
# current claims object {"key_1": 1, "key_2": 2}
stytch.sessions.authenticate(token, session_custom_claims={"key_1": null})
# resulting claims object {"key_2": 2}
Working with nested objects
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, session_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, session_custom_claims={
"e": {
"nested1": nil,
"nested3": "val3"
}
)
# resulting claims object
# {
# "c": 3.5,
# "d": 4,
# "e": {
# "nested2": "val2",
# "nested3": "val3"
# }
# }
Limitations
- Reserved claims: Certain claims are reserved and will result in an error if they are set (iss, sub, aud, exp, nbf, iat, jti, https://stytch.com/*)
- Size limit: Total custom claims size cannot exceed four kilobytes
- JWT immutability: Once a JWT is minted, it cannot be modified. You must authenticate again to update claims
What's next
- Learn about Custom Claim Templates
- Explore RBAC overview to understand role-based access control
- Set up your first Custom Claim Template
Any feedback? We'd love to hear it! Reach out to support@stytch.com.