如何在Flutter应用程序中从JWT获得索赔 [英] How to get the claims from a JWT in my Flutter Application

查看:208
本文介绍了如何在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));
}

这篇关于如何在Flutter应用程序中从JWT获得索赔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆