我有一个像这样的jwt令牌
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
Run Code Online (Sandbox Code Playgroud)
我如何解码这个,以便我可以像这样得到有效载荷
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Run Code Online (Sandbox Code Playgroud)
我使用过这个 库,却找不到办法做我想做的事
Ale*_*aos 49
你应该拆分字符串:如果你通过base 64解码器传递前两个部分,你将获得以下(为清晰起见,添加了格式):
头
{
"alg": "HS256",
"typ": "JWT"
}
Run Code Online (Sandbox Code Playgroud)
身体
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Run Code Online (Sandbox Code Playgroud)
代码示例:
public class JWTUtils {
public static void decoded(String JWTEncoded) throws Exception {
try {
String[] split = JWTEncoded.split("\\.");
Log.d("JWT_DECODED", "Header: " + getJson(split[0]));
Log.d("JWT_DECODED", "Body: " + getJson(split[1]));
} catch (UnsupportedEncodingException e) {
//Error
}
}
private static String getJson(String strEncoded) throws UnsupportedEncodingException{
byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);
return new String(decodedBytes, "UTF-8");
}
}
Run Code Online (Sandbox Code Playgroud)
例如,呼叫方法
JWTUtils.decoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");
Run Code Online (Sandbox Code Playgroud)
库参考:https: //github.com/jwtk/jjwt
jwt测试:https://jwt.io/
小智 6
我使用了一个名为JWTDecode.Android https://github.com/auth0/JWTDecode.Android的第三方库。文档是相当好的。根据您的问题,子名称,名称等是主体的一部分,被称为Claims。使用上面的库,您可以像这样获得它们:
JWT parsedJWT = new JWT(jwtToken);
Claim subscriptionMetaData = parsedJWT.getClaim("name");
String parsedValue = subscriptionMetaData.asString();
Run Code Online (Sandbox Code Playgroud)
这可以使用 Java 8 的 Base64 类来实现:
public String getDecodedJwt(String jwt)
{
String result = "";
String[] parts = jwt.split("[.]");
try
{
int index = 0;
for(String part: parts)
{
if (index >= 2)
break;
index++;
byte[] partAsBytes = part.getBytes("UTF-8");
String decodedPart = new String(java.util.Base64.getUrlDecoder().decode(partAsBytes), "UTF-8");
result += decodedPart;
}
}
catch(Exception e)
{
throw new RuntimeException("Couldnt decode jwt", e);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我在 Java Web 应用程序中使用了它,代码如下所示:-
Jwts.parser().setSigningKey('secret-key').parseClaimsJws(token).getBody()
Run Code Online (Sandbox Code Playgroud)
它将返回包含所需值的声明。