Skip to content

Instantly share code, notes, and snippets.

@gringoh
Last active May 12, 2022 14:54
Show Gist options
  • Save gringoh/3ba7cb853563396acbf5d0ae958a708d to your computer and use it in GitHub Desktop.
Save gringoh/3ba7cb853563396acbf5d0ae958a708d to your computer and use it in GitHub Desktop.
[Dart: decode JWT token] #dart #flutter
_decodeJwt(String jwt) {
final parts = jwt.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);
}
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));
}
@gringoh
Copy link
Author

gringoh commented Nov 19, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment