public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ActionDescriptor.EndpointMetadata.Any(em => em.GetType() == typeof(AllowAnonymousAttribute))) { return; } var request = context.HttpContext.Request; var hasApiKeyHeader = request.Headers.TryGetValue(ApiKeyConstants.HeaderName, out var apiKeyValue); if (!hasApiKeyHeader) { context.Result = new CustomUnauthorizedResult($"{ApiKeyConstants.HeaderName} header not found"); return; } if (apiKeyValue.Count == 0 || string.IsNullOrEmpty(apiKeyValue)) { context.Result = new CustomUnauthorizedResult($"{ApiKeyConstants.HeaderName} header is empty"); return; } if (await apiKeyService.IsAuthorizedAsync(apiKeyValue)) { var principal = CreatePrincipal(apiKeyValue); context.HttpContext.User = principal; return; } logger.LogError("API key \"{ApiKeyValue}\" is not valid", apiKeyValue); context.Result = new CustomUnauthorizedResult("Unauthorized"); }