如何在 android 中解码 JWT 令牌?

2022-01-10 00:00:00 jwt android java

我有一个像这样的 jwt 令牌

I have a jwt token like this

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

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

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

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

我使用过 this 库,但找不到做我想做的事情的方法p>

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

推荐答案

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

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):

标题

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

身体

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

代码示例:

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

调用方法举例<​​/p>

Call method for example

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

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

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

相关文章