jwtEncode function

String jwtEncode(
  1. Map<String, dynamic> data, {
  2. required String algorithm,
  3. required Key key,
})

Implementation

String jwtEncode(Map<String, dynamic> data, {required String algorithm, required Key key}) {
  _coerceAndValidateNumericDateIfPresent(String claim) {
    if (!data.containsKey(claim)) {
      return;
    }

    if (data[claim] is DateTime) {
      data[claim] = data[claim].toUtc().millisecondsSinceEpoch ~/ 1000;
    }

    if (!(data[claim] is int)) {
      throw FormatException("Claim \"$claim\" must be NumericDate");
    }
  }

  _coerceAndValidateNumericDateIfPresent('iat');
  _coerceAndValidateNumericDateIfPresent('nbf');
  _coerceAndValidateNumericDateIfPresent('exp');

  if (algorithm == 'EdDSA') {
    if (!(key is OkpKey)) {
      throw FormatException("EdDSA algorithm must use OKP key");
    }

    if (!(key is OkpPrivateKey)) {
      throw FormatException("Must encode with private key, not public key");
    }

    if (key.crv != 'Ed448') {
      throw UnsupportedError(
        "jwtEncode using the EdDSA algorithm currently only supports Ed448"
      );
    }

    return _ed448JwtEncode(data, key);
  } else {
    throw UnsupportedError("jwtEncode currently only supports EdDSA algorithm");
  }
}