JwtClaim.fromMap constructor

JwtClaim.fromMap(
  1. Map data, {
  2. bool defaultIatExp = true,
  3. Duration? maxAge,
})

Constructs a claim set from a Map of claims.

Normally, the Issued At and Expiration Time Claims will always be set. If they are not present in the data, default values are assigned to them. This behaviour is disabled when defaultIatExp is false. See the JwtClaim constructor for details of how defaultIatExp and maxAge control these default values.

Throws JwtException.invalidToken if the Map is not suitable.

Implementation

factory JwtClaim.fromMap(Map<dynamic, dynamic> data,
    {bool defaultIatExp = true, Duration? maxAge}) {
  final singleStringValue = <String, String>{};
  for (var claimName in ['iss', 'sub', 'jti']) {
    if (data.containsKey(claimName)) {
      final v = data[claimName];
      if (v is String) {
        singleStringValue[claimName] = v;
      } else {
        throw JwtException.invalidToken; // claim is not a StringOrURI
      }
    }
  }

  List<String>? audienceList;
  if (data.containsKey('aud')) {
    audienceList = <String>[];

    // The audience claim appears in the data
    final aud = data['aud'];
    if (aud is String) {
      // Special case when the JWT has one audience
      audienceList.add(aud);
    } else if (aud is List) {
      // General case
      for (var a in aud) {
        if (a is String) {
          audienceList.add(a);
        } else {
          throw JwtException.invalidToken; // list contains a non-string value
        }
      }
    } else {
      throw JwtException.invalidToken; // unexpected type for audience
    }
  }

  final expOrNull = JwtDate.decode(data['exp']);
  final notBeforeOrNull = JwtDate.decode(data['nbf']);
  final issuedAtOrNull = JwtDate.decode(data['iat']);

  // Extract all non-registered claims (including 'pld' if it is in the data)
  final others = <String, dynamic>{};
  data.forEach((k, v) {
    if (k is String) {
      if (!registeredClaimNames.contains(k)) {
        others[k] = v;
      }
    } else {
      throw JwtException.invalidToken; // Map had non-String as a key
    }
  });

  // Create a new JwtClaim and initialize with the registered claims
  return JwtClaim(
      issuer: singleStringValue['iss'],
      subject: singleStringValue['sub'],
      audience: audienceList,
      expiry: expOrNull,
      notBefore: notBeforeOrNull,
      issuedAt: issuedAtOrNull,
      jwtId: singleStringValue['jti'],
      otherClaims: (others.isNotEmpty) ? others : null,
      defaultIatExp: defaultIatExp,
      maxAge: maxAge);
}