【问题标题】:how to decode a token in dart如何在飞镖中解码令牌
【发布时间】:2019-01-21 04:10:54
【问题描述】:

谁能解释如何使用 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(token);

【问题讨论】:

  • 我认为这个插件会帮助pub.dartlang.org/packages/jwt
  • @Yamin Pub 说包裹不健康。
  • 也检查一下这个,pub.dartlang.org/packages/jaguar_jwt。如果它不能正常工作,我会写另一个插件。
  • 我发现这些软件包中没有一个有用——出于某种原因,他们需要密钥来解码 JWT .. 这没有任何意义,也不现实。我仍在寻找如何从我从服务器接收的 JWT 中获取声明...
  • @bofomar 对我提出的同一个问题发表了很棒的回应。这是该响应的链接,对我来说非常有用:Precise answer to decoding a JWT in Dart 2

标签: dart flutter


【解决方案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));
 }

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 2020-10-10
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2020-09-12
    • 2020-11-28
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多