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

调用方法举例

Call method for example

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

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

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)