本文介紹了如何在 android 中解碼 JWT 令牌?的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問題描述
我有一個(gè)像這樣的 jwt 令牌
I have a jwt token like this
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
我怎樣才能解碼這個(gè),這樣我才能得到這樣的有效載荷
How can I decode this so that I can get the payload like this
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
我使用過 this 庫(kù),但找不到做我想做的事情的方法p>
I have used this library , but can't find a way to do what I want
推薦答案
你應(yīng)該拆分字符串:如果您通過 base 64 解碼器傳遞前兩個(gè)部分,您將得到以下內(nèi)容(為清晰起見添加了格式):
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):
標(biāo)題
{
"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");
}
}
調(diào)用方法舉例?/p>
Call method for example
JWTUtils.decoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");
庫(kù)參考:https://github.com/jwtk/jjwt
jwt 測(cè)試:https://jwt.io/
這篇關(guān)于如何在 android 中解碼 JWT 令牌?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!