We have a Net Core 2.1 API project. We use the request headers to retrieve API key which we check against our database to see if it matches one of the expected keys. If it does then we allow the request to continue, otherwise we want to send back Unauthorized response.
our startup.cs
services.AddAuthorization(options =>
{
options.AddPolicy("APIKeyAuth", policyCorrectUser =>
{
policyCorrectUser.Requirements.Add(new APIKeyAuthReq());
});
});
services.AddSingleton<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, APIKeyAuthHandler>();
Our APIKeyAuthHandler.cs
public class APIKeyAuthReq : IAuthorizationRequirement { }
public class APIKeyAuthHandler : AuthorizationHandler<APIKeyAuthReq>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, APIKeyAuthReq requirement)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (requirement == null)
throw new ArgumentNullException(nameof(requirement));
var httpContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var headers = httpContext.HttpContext.Request.Headers;
if (headers.TryGetValue("Authorization", out Microsoft.Extensions.Primitives.StringValues value))
{
using (DBContext db = new DBContext ())
{
var token = value.First().Split(" ")[1];
var login = db.Login.FirstOrDefault(l => l.Apikey == token);
if (login == null)
{
context.Fail();
httpContext.HttpContext.Response.StatusCode = 403;
return Task.CompletedTask;
} else
{
httpContext.HttpContext.Items.Add("CurrentUser", login);
context.Succeed(requirement);
return Task.CompletedTask;
}
}
}
}
}
and our controller.cs
[Route("api/[controller]/[action]")]
[Authorize("APIKeyAuth")]
[ApiController]
public class SomeController : ControllerBase
{
}
Everything works fine when a valid key exists but when it doesnt, there is a 500 internal error thrown for No authenticationScheme instead of 403.
We are relatively new to net core (coming from Net Framework/Forms Authentication) so if there is more accurate way of doing this sort of auth, please let me know.
Error Message:
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)