private async Task TryAuthenticateApiKey(HttpContext context, string apiKeyHeaderValue) { var externalSystem = _apiKeyService.GetExternalServiceByApiKey(apiKeyHeaderValue); if (externalSystem == null) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await context.Response.WriteAsync("Invalid API Key"); } var controllerAction = GetControllerAction(context); if (!externalSystem.CanAccessControllerAction(controllerAction)) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("You have no access to perform this action"); } SetCurrentApiKeyPrincipal(context, externalSystem); }