如何在我的 Flutter 应用程序中从 JWT 获取声明 [英] How to get the claims from a JWT in my Flutter Application

查看:32
本文介绍了如何在我的 Flutter 应用程序中从 JWT 获取声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 Flutter/Dart 应用程序,并从身份验证服务器获取 JWT,其中有一些我需要使用的声明.我已经查看了各种(到目前为止有 4 个)Dart JWT 库——但它们要么太旧,不再与 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天全站免登陆