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

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

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

Tags:

Dart

Jwt

Flutter