Flutter: How to decode JWT token using Dart?
1 min readMay 14, 2020
JWT tokens are 3 Base64 strings separated by “.”.
- Part 1 is called Header. it contains an algorithm and token type.
- Part 2 is called Payload. it contains user data.
- Part 3 is called Signature. Which is calculated like following:
<Hashing Algo: e.g. HMACSHA256 etc>(
base64UrlEncode(header) + "." + base64UrlEncode(payload), "secret string<Known to JWT creator>"
);
As a Application developer we are mostly interested in decoding the Payload to get User Details like mail-id, session time etc. So we start by splitting the JWT in 3 parts.
final parts = token.split('.');
if (parts.length != 3) {
throw Exception('invalid token');
}
Now, Decode Base64 encoded string to get Payload JSON.
import 'dart:convert';String decodeBase64(String str) {
//'-', '+' 62nd char of encoding, '_', '/' 63rd char of encoding
String output = str.replaceAll('-', '+').replaceAll('_', '/'); switch (output.length % 4) { // Pad with trailing '='
case 0: // No pad chars in this case
break;
case 2: // Two pad chars
output += '==';
break;
case 3: // One pad char
output += '=';
break;
default:
throw Exception('Illegal base64url string!"');
}
return utf8.decode(base64Url.decode(output));
}
Above function will return Json string with Payload.
//0: Header, 1: Payload, 2: Signature
final payload = _decodeBase64(parts[1]);
final payloadMap = json.decode(payload); //Map dictionary
Complete Code: