'Is there any part of JWT Keycloak token which can be used as a unique ID of the token itself?
Edit
My question was before about Keycloak token only, but the solution I found is more general, it is applicable for JWT regardless of Keycloak.
Background / Motivation
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.
Question
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.
Solution 1:[1]
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. Thejticlaim can be used to prevent the JWT from being replayed. Thejtivalue 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.
Solution 2:[2]
Based on your use case, two fields I can think of using is id / email id and expiration.
Id / email id is unique and always present, so that serves your purpose.
Expiration alone cannot be used as 2 tokens generated for 2 users at same time may have same expiration. Then why am I asking to use? If your cache does not support TTL, then there might be stale entries unnecessarily occupying your cache. So if you keep your key as "expiration.id", then you can maybe run a side job every 24 hours or so to delete stale entries from cache , based on first part i.e. expiration.
Here is sample Keycloak token object in my Java app:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |

