如何在Flutter应用程序中从JWT获得索赔

如何在Flutter应用程序中从JWT获得索赔

问题描述:

我正在编写Flutter/Dart应用程序,并从具有某些需要使用的声明的身份验证服务器取回JWT.我看过各种Dart JWT库(到目前为止有4个),但是它们要么都太旧了,不能再与Dart 2一起使用,等等,或者它们需要解密JWT的秘密,这是没有道理的,也是不正确的(或有可能,因为我无权访问).

I am writing a Flutter/Dart application and am getting a JWT back from an auth server that has some claims I need to use. I have looked at various (4 so far) Dart JWT libraries -- but all are either too old and no longer work with Dart 2, etc. or they need the secret to decode the JWT which makes no sense and isn't correct (or possible since I have no access ).

那么-如何在现代" Dart/Flutter应用程序中获得JWT并从中获得要求?

So -- how can one get a JWT and get the claims from it within a "modern" Dart/Flutter application?

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

JWT tokens are just base64 encoded JSON strings (3 of them, separated by dots):

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