解析 JWT 令牌有效负载数据以在 android/java 中获取特定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39822385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:39:48  来源:igfitidea点击:

Parse JWT token payload data to get certain value in android/java

javaandroidjwt

提问by Gaurav Sarma

I just got introduced to the JWT and wanted to know how to parse the payload data to get a certain value from it using the key.

我刚刚接触了 JWT,想知道如何使用密钥解析有效负载数据以从中获取特定值。

Example in the following JWT token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

以下 JWT 令牌中的示例 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV5OrabHEVEhgrxV5OrabHEVEhgrx7FJFYcYcFYcYcFYcYcFYcYcFYcYcFYcYcFJEh7

The payload data contains the following object when decoded in jwt.io

在 jwt.io 中解码时,payload 数据包含以下对象

{
    "sub" : "1234567890"
    "name" : "John Doe"
    "admin" : "true"
}  

I want to be able to parse this object to get the value of name which in this case is John Doe from the above JWT token.

我希望能够解析这个对象以获取 name 的值,在这种情况下是来自上述 JWT 令牌的 John Doe。

I have already read this Android JWT parsing payload/claims when signed

我已经阅读了这个Android JWT 签名时解析有效负载/声明

But i wanted to know if there is efficient way to do this in android using some library. Any help would be appreciated.

但我想知道是否有有效的方法在 android 中使用某个库来做到这一点。任何帮助,将不胜感激。

采纳答案by Gaurav Sarma

I solved it, by normally parsing the string and decoding it from base64 and then casting the string to JSONObject and parsing the JSONObject to get the required value.

我解决了这个问题,方法是通常解析字符串并从 base64 解码它,然后将字符串转换为 JSONObject 并解析 JSONObject 以获得所需的值。

回答by Janus Varmarken

You can use Java JWTfor that:

您可以为此使用Java JWT

String name = Jwts.parser().setSigningKey(keyUsedWhenSigningJwt).parseClaimsJws("base64EncodedJwtHere").getBody().get("name", String.class);