Created
March 26, 2020 08:03
-
-
Save fida1989/fcede5ec8c81157f9baf3ead588f5a0d to your computer and use it in GitHub Desktop.
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'; | |
class JWTUtils { | |
static final instance = JWTUtils(); | |
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'); | |
} | |
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment