How can I decode JWT token in android?(如何在 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 令牌?
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01