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

问题描述 投票:5回答:2

我正在编写一个Flutter / Dart应用程序,并从一个具有我需要使用的声明的auth服务器返回JWT。我已经看过各种各样的(4个到目前为止)Dart JWT库 - 但是它们都太旧了,不再使用Dart 2等,或者它们需要秘密来解码JWT,这没有任何意义且不正确(或者可能,因为我没有访问权限)。

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

dart jwt flutter
2个回答
23
投票

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));
}

0
投票

在撰写本文时,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);

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

{
  "exp":1554820162,
  "iat":1554776962,
  "iss":"Suragch",
  "sub":"4"
}

See also:


0
投票

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

String getJsonFromJWT(String splittedToken){
  String normalizedSource = base64Url.normalize(encodedStr);
  return utf8.decode(base64Url.decode(normalizedSource));
}
© www.soinside.com 2019 - 2024. All rights reserved.