Java 如何在 android 中解码 JWT 令牌?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37695877/
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-08-11 19:34:17  来源:igfitidea点击:

How can I decode JWT token in android?

javaandroidjwt

提问by aroM

I have a jwttoken like this

我有一个像这样的jwt令牌

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

How can I decode this so that I can get the payload like this

我怎样才能解码这个以便我可以得到这样的有效载荷

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

I have used thislibrary , but can't find a way to do what I want

我已经使用过这个库,但找不到做我想做的事情的方法

回答by Apollo

I've used in a Java web application and the code will look something like below :-

我在 Java Web 应用程序中使用过,代码如下所示:-

Jwts.parser().setSigningKey('secret-key').parseClaimsJws(token).getBody()

It will return claims which contains the required values.

它将返回包含所需值的声明。

回答by Alex Zaraos

you should split string: If you pass the first two sections through a base 64 decoder, you'll get the following (formatting added for clarity):

您应该拆分字符串:如果您通过 base 64 解码器传递前两个部分,您将获得以下内容(为了清晰起见,添加了格式):

header

标题

{
  "alg": "HS256",
  "typ": "JWT"
}

body

身体

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

Code example:

代码示例:

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");
    }
}

Call method for example

调用方法为例

JWTUtils.decoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");

library reference: https://github.com/jwtk/jjwt

库参考:https: //github.com/jwtk/jjwt

jwt test: https://jwt.io/

jwt 测试:https://jwt.io/

回答by diptia

I used a third party library named JWTDecode.Android https://github.com/auth0/JWTDecode.Android. The documentation is reasonably good . From your question , The sub , name etc are a part of the body and are called Claims . You could get them like this using the above library :

我使用了一个名为 JWTDecode.Android https://github.com/auth0/JWTDecode.Android 的第三方库。文档相当不错。根据您的问题, sub 、 name 等是 body 的一部分,称为 Claims 。你可以使用上面的库得到它们:

  JWT parsedJWT = new JWT(jwtToken);
  Claim subscriptionMetaData = parsedJWT.getClaim("name");
  String parsedValue = subscriptionMetaData.asString();

回答by Brad Parks

This works using Java 8's Base64 class:

这适用于 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;
}

回答by imdev

If the project is already using AWSCognito SDK then CognitoJWTParserclass can be used. It has static methods getHeader(), getPayload(), getSignature().

如果项目已在使用 AWSCognito SDK,则CognitoJWTParser可以使用类。它有静态方法getHeader(), getPayload(), getSignature()

https://github.com/aws-amplify/aws-sdk-android/blob/master/aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/util/CognitoJWTParser.java

https://github.com/aws-amplify/aws-sdk-android/blob/master/aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/util/CognitoJWTParser.java