JWT Keycloak 令牌中是否有任何部分可以用作令牌本身的唯一 ID?

Is there any part of JWT Keycloak token which can be used as a unique ID of the token itself?

编辑

我之前的问题只是关于 Keycloak 令牌,但我找到的解决方案更通用,它适用于 JWT,与 Keycloak 无关。

背景/动机

基于 JWT Keycloak 令牌,我从我的数据库中获取用户的一些附加信息(sub 字段)。我想缓存信息,我正在寻找合适的缓存键。

我不想使用 sub 字段,因为我希望缓存条目在 Keycloak 令牌更改时失效(= 当为同一用户生成新令牌时)。

我可以轻松地使用整个 Keycloak 令牌或其第三方(签名)作为密钥。但是,它是一个很长的字符串。

问题

JWT Keycloak 令牌中是否有任何 字段,可用作此特定令牌的唯一 ID?保证始终存在,并且始终针对令牌的新实例进行更改。

sid字段是这样工作的吗?至少看起来和sub.

不一样

Keycloak 令牌中有几个 UUID,我对文档感到困惑。我只找到这个 clearly arranged table 解释 Keycloak 令牌字段的含义。

根据您的用例,我可以想到使用的两个字段是 id / email id 和过期时间。

  1. ID / 电子邮件 ID 是唯一的并且始终存在,因此符合您的目的。

  2. 不能单独使用过期,因为同时为 2 个用户生成的 2 个令牌可能具有相同的过期时间。那我为什么要使用?如果您的缓存不支持 TTL,则可能有过时的条目不必要地占用您的缓存。因此,如果您将密钥保留为“expiration.id”,那么您可能 运行 每 24 小时左右执行一次副业,以根据第一部分即过期时间从缓存中删除过时的条目。

这是我的 Java 应用程序中的示例 Keycloak 令牌对象:

终于找到了JWT的详细文档:https://datatracker.ietf.org/doc/html/rfc7519

该字段不是密钥斗篷特定的,它在 JWT 标准中定义。

指定field jti为:

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. The jti claim can be used to prevent the JWT from being replayed. The jti value is a case-sensitive string. Use of this claim is OPTIONAL.

该字段完全符合我“提供此特定令牌的唯一 ID”的要求。而且我们的 keycloak 服务器似乎为该字段分配了一个 UUID。