Java从JWT令牌中获取主题

huangapple go评论76阅读模式
英文:

Java get subject from JWT token

问题

我想读取JWT令牌,并从中获取userID。

据我所知,userID等于JWT声明中的"sub",即"subject"。

@GET()
@Path("path")
@RolesAllowed("user")
public String method( ){

    String userID = jwt.claims.get("sub");  // 或类似的代码

}

有可能实现吗?

英文:

I would like to read the JWT token, and get the userID from it.

As I know the userID is equal to "sub" as "subject" in the JWT claims.

@GET()
@Path("path")
@RolesAllowed("user")
public String method(    ){

    String userID = jwt.claims.get ("sub");  // or something like this 

}

How is it possible?

答案1

得分: 2

如果userID在“sub”声明中,您可以使用库按以下方式接收它:

Long userID = Long.parseLong(Jwts.parser()
  .setSigningKey(secretKey)
  .parseClaimsJws(token)
  .getBody()
  .getSubject());

其中secretKey是您的签名密钥,token是您的JWT令牌。

英文:

If the userID is in the "sub" claim, you can receive it in the following way using this library:

Long userID = Long.parseLong(Jwts.parser()
  .setSigningKey(secretKey)
  .parseClaimsJws(token)
  .getBody()
  .getSubject());

Where secretKey is your signing key and token is your JWT token.

huangapple
  • 本文由 发表于 2020年5月3日 18:47:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/61573180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定