如何在我的Flutter应用程序中获取JWT的声明

sjm*_*all 15 jwt dart flutter

我正在编写一个Flutter/Dart应用程序,并从一个具有我需要使用的声明的auth服务器返回JWT.我看过各种(4至今)飞镖JWT库 - 但都太旧,并不再与飞镖2等工作,或者他们需要的秘密智威汤逊这是没有意义的,是不正确(解码或者可能,因为我没有访问权限).

那么 - 如何在"现代"的Dart/Flutter应用程序中获得JWT并从中获取声明?

bof*_*mer 33

JWT令牌只是base64编码的JSON字符串(其中3个用点分隔):

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 太棒了。就是让我感到困惑的填充-这是一个非常好的例程-谢谢!现在,为什么这个小例程不在一个不错的JWT包中,我不知道!:)(或者如果不容易看到它!) (2认同)

TGL*_*LEE 8

使用“base64Url.normalize()”函数。这就是 _decodeBase64() 从上面的答案中所做的!

String getJsonFromJWT(String splittedToken){
  String normalizedSource = base64Url.normalize(encodedStr);
  return utf8.decode(base64Url.decode(normalizedSource));
}
Run Code Online (Sandbox Code Playgroud)


Sur*_*gch 5

截至撰写本文时,jaguar_jwt包正在积极维护中。尽管没有明确记录,但它确实有一个公共方法可以解码 Base64Url 编码。它的作用与已接受的答案基本相同。

//import 'package:jaguar_jwt/jaguar_jwt.dart';

final String token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTQ4MjAxNjIsImlhdCI6MTU1NDc3Njk2MiwiaXNzIjoiU3VyYWdjaCIsInN1YiI6IjQifQ.bg5B_k9WCmxiu2epuZo_Tpt_KZC4N9ve_2GEdrulcXM';
final parts = token.split('.');
final payload = parts[1];
final String decoded = B64urlEncRfc7515.decodeUtf8(payload);
Run Code Online (Sandbox Code Playgroud)

这给出了一个 JSON 字符串,对于这个特定的示例来说是:

{
  "exp":1554820162,
  "iat":1554776962,
  "iss":"Suragch",
  "sub":"4"
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


Iva*_*nda 3

您可以使用jwt_decoder包来解码和/或检查您的令牌是否已过期

 //to get claims from your token
 main () {
   String yourToken = "Your JWT";
   Map<String, dynamic> decodedToken = 
   JwtDecoder.decode(yourToken);

   /*
   If the token has a valid format, you will get a 
   Map<String,dynamic> Your decoded token can look like:
   {
     "sub": "1234567890",
     "name": "Gustavo",
     "iat": 1516239022,
     "exp": 1516239022,
     "randomKey": "something else"
    }
    */
 }

//check if your token is expired
main () {
 String yourToken = "Your JWT";
 bool hasExpired = JwtDecoder.isExpired(yourToken);

 // You will get a true / false response
 // true: if the token is already expired
 // false: if the token is not expired
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方式获取令牌到期日期

main () {
 String yourToken = "Your JWT";
 DateTime expirationDate = JwtDecoder.getExpirationDate(token);

 // 2025-01-13 13:04:18.000
 print(expirationDate);
}
Run Code Online (Sandbox Code Playgroud)

您还可以了解您的令牌有多久了

// Token payload must include an 'iat' field
main () {
 String yourToken = "Your JWT";
 Duration tokenTime = JwtDecoder.getTokenTime(token);

 // 15
 print(tokenTime.inDays);
}
Run Code Online (Sandbox Code Playgroud)

要了解有关JWT Decoder功能的更多信息,请访问其包文档页面