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

后端 未结 3 752
旧时难觅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:49

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

    import 'dart:convert';
    
    Map 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) {
        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));
    }
    

提交回复
热议问题