如何在 android 中解码 JWT 令牌?

How can I decode JWT token in android?(如何在 android 中解码 JWT 令牌?)

本文介绍了如何在 android 中解码 JWT 令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 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/

这篇关于如何在 android 中解码 JWT 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 android 中解码 JWT 令牌?