defaultJwtCodec method

JwtCodec defaultJwtCodec()

Builds the codec described by config.

Implementation

JwtCodec defaultJwtCodec() {
  final keys = <JwtKey>[];
  final publicKey = config.jwtPublicKey;
  if (config.jwtAlgorithm == .eddsa) {
    if (publicKey == null || publicKey.isEmpty) {
      throw const ConfigException(
        'JWT_ALGO=EdDSA requires JWT_PUBLIC_KEY (and JWT_PRIVATE_KEY to '
        'sign). Generate them with `dartisan jwt:keygen`.',
      );
    }
    final seed = config.jwtPrivateKey;
    keys.add(
      Ed25519JwtKey(
        publicKey: base64.decode(publicKey),
        seed: seed == null || seed.isEmpty ? null : base64.decode(seed),
        kid: config.jwtKid,
      ),
    );
  } else {
    final secret = config.jwtSecret ?? _appKey;
    if (secret == null || secret.isEmpty) {
      throw const ConfigException(
        'JWT guards need JWT_SECRET (or APP_KEY) to sign HS256 tokens.',
      );
    }
    final bytes = secret.startsWith('base64:')
        ? Encrypter.parseKey(secret)
        : utf8.encode(secret);
    if (bytes.length < 32) {
      throw ConfigException(
        'JWT_SECRET must be at least 32 bytes (256 bits) for HS256; '
        'got ${bytes.length}. Generate one with `dartisan key:generate`.',
      );
    }
    keys.add(HmacJwtKey(bytes, kid: config.jwtKid));
  }
  return JwtCodec(
    keys: keys,
    leeway: config.jwtLeeway,
    issuer: config.jwtIssuer,
    audience: config.jwtAudience,
  );
}