decodeToken function

Map<String, dynamic> decodeToken(
  1. String token
)

The claims in token's payload.

Throws a FormatException describing what was wrong, rather than the bare Error() this used to raise, which told a caller nothing and could not be caught as an Exception.

Returns a Map<String, dynamic> rather than dynamic: reading a claim off a dynamic is a dynamic call, which no analyzer setting can check, and this is the one place in the package that produced them.

Implementation

Map<String, dynamic> decodeToken(String token) {
  final parts = token.split('.');
  if (parts.length != 3) {
    throw FormatException(
      'Not a JWT: expected three dot-separated parts, got ${parts.length}',
    );
  }

  final dynamic payload;
  try {
    payload = jsonDecode(_urlBase64Decode(parts[1]));
  } on FormatException {
    rethrow;
  } catch (err) {
    throw FormatException('The token payload could not be read: $err');
  }

  if (payload is! Map<String, dynamic>) {
    throw const FormatException('The token payload is not a JSON object');
  }

  return payload;
}