如何在Android中解码JWT令牌? [英] How can I decode JWT token in android?

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

问题描述

我有一个 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 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");
    }
}

例如调用方法

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

图书馆参考: https://github.com/jwtk/jjwt

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆