-
-
Save betoflakes/e2c320152bc0b65572c4c2e9dffd2ab6 to your computer and use it in GitHub Desktop.
Get payload of JWT token in Dart language
This file contains 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
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