decodeJwt function

Map<String, dynamic> decodeJwt(
  1. String jwt
)

Decodes the payload of a compact-serialized jwt into its JSON claims.

Throws a FormatException if jwt is not a valid three-segment JWS, has an empty payload, or cannot be base64url/JSON decoded.

Implementation

Map<String, dynamic> decodeJwt(String jwt) {
  final parts = jwt.split('.');
  if (parts.length == 5) {
    throw const FormatException(
      'Only JWTs using Compact JWS serialization can be decoded',
    );
  }
  if (parts.length != 3) {
    throw const FormatException('Invalid JWT');
  }

  final payload = parts[1];
  if (payload.isEmpty) {
    throw const FormatException('JWTs must contain a payload');
  }

  Uint8List decoded;
  try {
    decoded = base64Url.decode(base64Url.normalize(payload));
  } catch (_) {
    throw const FormatException('Failed to base64url decode the payload');
  }

  try {
    final jsonPayload = utf8.decode(decoded);
    return jsonDecode(jsonPayload) as Map<String, dynamic>;
  } catch (e) {
    throw FormatException('Failed to decode JWT: $e');
  }
}