I am trying to implement a simple api key based authentication handler. My handler method is
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Get the apiKey from a store...
if (apiKey != header.Parameter)
{
var error = "Invalid username or api key.";
return Task.FromResult(AuthenticateResult.Fail(error));
}
var claims = new List<Claim> {new Claim("user", (string)username)};
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, header.Scheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
When I make the request with the correct username and the api key, the method above returns AuthenticateResult.Success(ticket)
as expected. However, my controller action is not getting invoked despite being correctly authenticated. Instead, the Task HandleChallengeAsync(AuthenticationProperties properties)
is getting called and is returning 401 unauthorised response.
I'm registering my authentication handler in startup class like:
public void ConfigureServices(IServiceCollection services)
{
// register controllers, etc.
services.AddAuthentication("ApiKey").AddApiKeyBearer();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
IHostApplicationLifetime applicationLifetime)
{
app.ConfigureExceptionHandler()
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(builder => builder.MapControllers());
}
How can I avoid the challenge since the authentication is already successful?
I managed to find out the answer here. Basically, I needed to override the default authorization policy in the startup class like so
services.AddAuthorization(o =>
{
var builder = new AuthorizationPolicyBuilder("ApiKey);
builder = builder.RequireClaim("user");
o.DefaultPolicy = builder.Build();
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments