首页 > 解决方案 > 如何在飞镖中解码令牌

问题描述

任何人都可以解释如何使用 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);

标签: dartflutter

解决方案


如果您有兴趣获得令牌的公共部分,基本上您必须将令牌拆分为“。” 并用 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));
 }

推荐阅读