parseApiKeyRequest function
Parses API-key headers while distinguishing a missing credential from a malformed recognized authorization scheme.
A non-blank value in headerName takes precedence over Authorization.
Blank direct-header values fall back to Authorization: ApiKey <key>;
scheme matching is case-insensitive. Unsupported authorization schemes are
treated as absent, while a recognized scheme without a key sets
AuthApiKeyRequest.malformed.
Implementation
AuthApiKeyRequest parseApiKeyRequest(
EngineContext ctx, {
String headerName = 'x-api-key',
}) {
final direct = ctx.request.header(headerName).trim();
if (direct.isNotEmpty) return AuthApiKeyRequest(value: direct);
final authorization = ctx.request
.header(HttpHeaders.authorizationHeader)
.trim();
if (authorization.isEmpty) return const AuthApiKeyRequest();
final separator = RegExp(r'\s').firstMatch(authorization);
final scheme = separator == null
? authorization
: authorization.substring(0, separator.start);
if (scheme.toLowerCase() != 'apikey') return const AuthApiKeyRequest();
if (separator == null) return const AuthApiKeyRequest(malformed: true);
final value = authorization.substring(separator.end).trim();
if (value.isEmpty) return const AuthApiKeyRequest(malformed: true);
return AuthApiKeyRequest(value: value);
}