How to get the claims from a JWT in my Flutter Application

后端 未结 3 753
旧时难觅i
旧时难觅i 2020-12-15 18:55

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 libra

相关标签:
3条回答
  • 2020-12-15 19:40

    Use 'base64Url.normalize()' function. That's what _decodeBase64() does from the answer above!

    String getJsonFromJWT(String splittedToken){
      String normalizedSource = base64Url.normalize(encodedStr);
      return utf8.decode(base64Url.decode(normalizedSource));
    }
    
    0 讨论(0)
  • 2020-12-15 19:47

    As of this writing, the jaguar_jwt package is being actively maintained. Although it is not clearly documented, it does have a public method that will decode Base64Url encoding. It does basically the same thing as the accepted answer.

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

    This gives a JSON string, which for this particular example is:

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

    See also:

    • JWT: The Complete Guide to JSON Web Tokens
    • String based data encoding: Base64 vs Base64url
    0 讨论(0)
  • 2020-12-15 19:49

    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));
    }
    
    0 讨论(0)
提交回复
热议问题