I have Web API developed using ASP.NET Core and I need to be able to use both Basic and Bearer authentication schemes for the same service. For some reason it does not work: it always considers the call as a bearer one. Here's my code:
This are the attributes I have in the controller:
[Authorize(ActiveAuthenticationSchemes = "Basic,Bearer")]
[ResponseCache(NoStore = true, Duration = 0, VaryByHeader = "Authorization")]
This is my startup.cs:
this part is for basic auth:
app.UseBasicAuthentication(new BasicAuthenticationOptions
{
AutomaticAuthenticate = false,
AutomaticChallenge = false,
Realm = "test",
Events = new BasicAuthenticationEvents
{
OnValidateCredentials = context =>
{
if (svc.IsValidCredential(context.Username, context.Password))
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, context.Username),
new Claim(ClaimTypes.Name, context.Username)
};
context.Ticket = new AuthenticationTicket(
new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Options.AuthenticationScheme)),
new AuthenticationProperties(),
context.Options.AuthenticationScheme);
}
return Task.FromResult<object>(null);
}
}
});
And this piece of code for Bearer authentication:
app.UseAPIKeyAuthentication(new BearerApiKeyOptions
{
AuthenticationScheme = BearerApiKeySchema,
AutomaticAuthenticate = false
});