谁能解释如何使用dart解码json中的令牌。
我用以下代码在android中完成了操作。但是如何在dart中解码令牌。
public class JWTUtils {
public static String decoded(String JWTEncoded) throws Exception {
String encode = "";
try {
String[] split = JWTEncoded.split("\\.");
Log.d("JWT_DECODED", "Header: " + getJson(split[0]));
encode = getJson(split[1]);
} catch (UnsupportedEncodingException e) {
//Error
}
return encode;
}
private static String getJson(String strEncoded) throws UnsupportedEncodingException{
byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);
return new String(decodedBytes, "UTF-8");
}
}
字符串编码数据= JWTUtils.decoded(令牌);
答案 0 :(得分:1)
如果您有兴趣获取令牌的公共部分,则必须将令牌用'。'分隔。并使用base64解码第二部分
var text = token.split('.')[1];
var decoded = base64.decode(text);
return utf8.decode(decoded);
import 'dart:convert';
Map<String, dynamic> parseJwt(String token) {
final parts = token.split('.');
if (parts.length != 3) {
throw Exception('invalid token');
}
final payload = _decodeBase64(parts[1]);
final payloadMap = json.decode(payload);
if (payloadMap is! Map<String, dynamic>) {
throw Exception('invalid payload');
}
return payloadMap;
}
String _decodeBase64(String str) {
String output = str.replaceAll('-', '+').replaceAll('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw Exception('Illegal base64url string!"');
}
return utf8.decode(base64Url.decode(output));
}