My question was originally before about Keycloak token only, but the solution I found is applicable for JWT in general, regardless of Keycloak.
Based on the JWT Keycloak token, I fetch some additional information of the user (the sub
field) from my database. I'd like to cache the information and I am looking for an appropriate key to the cache.
I do not want to use the sub
field because I want the cache entry to invalidate when the Keycloak token changes (= when a new token is generated for the same user).
I can easily use the whole Keycloak token or its third part (the signature) as the key. However, it is quite a long string.
Is there any field in the JWT Keycloak token, which may be used as a unique ID of this particular token? Which is guaranteed to be always present, and always change for a new instance of the token.
Does the sid
field work like this? At least it seems to be different from sub
.
There are several UUIDs in the Keycloak token and I am confused by the documentation. I found only this clearly arranged table explaining the meaning of the Keycloak token fields.
Finally I found the detailed documentation of JWT: https://datatracker.ietf.org/doc/html/rfc7519
The field is not keycloak specific, it is defined in the JWT standard.
There is specified the field jti
as:
The
jti
(JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. Thejti
claim can be used to prevent the JWT from being replayed. Thejti
value is a case-sensitive string. Use of this claim is OPTIONAL.
The field exactly matches my requirement to "provide a unique ID of this particular token". And it seems that our keycloak server assigns the field a UUID.
The documentation even suggests using the field as a cache key by saying that
the
jti
claim can be used to prevent the JWT from being replayed,
which is exactly what I needed.