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

19,064

Solution 1

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

Solution 2

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

Solution 3

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:

Share:
19,064

Related videos on Youtube

sjmcdowall
Author by

sjmcdowall

World traveling and technology loving coder at heart. Years of experience in lots of various technologies, but more a jack of all trades master of none (these days). Love doing the NYT Crossword puzzle, reading, and playing guitar.

Updated on June 07, 2022

Comments

  • sjmcdowall
    sjmcdowall almost 2 years

    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 ).

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

  • sjmcdowall
    sjmcdowall over 5 years
    This is PERFECT. It was the padding that was confusing me -- this is a very nice routine -- thank you! Now, why this little routine isn't in a nice JWT package I have no idea! :) (Or if it is it's not easy to see!)
  • boformer
    boformer over 5 years
    I think I just took it from one of the Dart 1 JWT packages, added a few types, lowercase constants...
  • BIS Tech
    BIS Tech about 5 years
    Thank you It worked for me. I print utf8.decode(base64url.decode(output)).. the result is String. How do I get only one key-value?
  • boformer
    boformer about 5 years
    when you run parseJwt(), you get a Map result. Use map['key'] to get the value for a key.
  • Ragesh S
    Ragesh S over 4 years
    I have one question about JWT using with flutter application, if we have a large users ( 1 to 2 lakhs users ) in our mobile application is there any problem or which is the maximum number of users, that are allowed in JWT implementation.