dart - 如何在飞镖中解码令牌
问题描述
任何人都可以解释如何使用 dart 解码 json 中的令牌。
我用下面的代码在android中完成了。但是如何在飞镖中解码一个令牌。
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(token);
解决方案
如果您有兴趣获得令牌的公共部分,基本上您必须将令牌拆分为“。” 并用 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));
}
推荐阅读
- javascript - offie-js Word Web 插件:可以动态添加菜单项
- install4j - 使用 Install4J 生成 Windows 可执行文件,JDK11 单独工作
- python - 是否可以在 manim 的图形对象上使用 ReplacementTransform?
- javascript - Prevent Multiple Instances for SetInterval
- php - Foreach array of objects in PHP
- kofax - 唯一的 KTA 作业名称
- javascript - How to import typescript file into script tag
- android - Is it possible to convert android/iOS app in cross platform app?
- r - R Shiny - create internal link to another element of my app
- asp.net-core - How I can Use IUserIdPriver? where am I doing wrong?