jwtDecode function
Decode a JWT without verifying its signature. Returns the payload, or the
header when header is true.
Implementation
Map<String, dynamic> jwtDecode(String token, {bool header = false}) {
final pos = header ? 0 : 1;
final parts = token.split('.');
if (parts.length <= pos) {
throw InvalidTokenError(
'Invalid token specified: missing part #${pos + 1}',
);
}
String decoded;
try {
decoded = _base64UrlDecode(parts[pos]);
} catch (e) {
throw InvalidTokenError(
'Invalid token specified: invalid base64 for part #${pos + 1} ($e)',
);
}
try {
return jsonDecode(decoded) as Map<String, dynamic>;
} catch (e) {
throw InvalidTokenError(
'Invalid token specified: invalid json for part #${pos + 1} ($e)',
);
}
}