Last active
May 12, 2022 14:54
-
-
Save gringoh/3ba7cb853563396acbf5d0ae958a708d to your computer and use it in GitHub Desktop.
[Dart: decode JWT token] #dart #flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
source: https://stackoverflow.com/a/58612911