Skip to content

Instantly share code, notes, and snippets.

@hjJunior
Created January 15, 2019 18:00
Show Gist options
  • Save hjJunior/2fd180c703919fc4bca8337ac3c56268 to your computer and use it in GitHub Desktop.
Save hjJunior/2fd180c703919fc4bca8337ac3c56268 to your computer and use it in GitHub Desktop.
Get payload of JWT token in Dart language
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');
}
print(payloadMap);
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));
}
void main() {
parseJwt(
"eyJhbGciOiJIUzI1NiJ9.eyJ1c3VhcmlvX2xvZ2dlZCI6MSwiYWRtaW4iOnRydWUsImV4cCI6MTU0ODE3ODY2Nn0.lAzR0RkP1MXYjOwYkUkVJC2FFIgu7LwWjwB_uA6QSjw");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment