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
});
You may look at this for some reference from official Microsoft GitHub.
My use-case is slightly different, I need a combination of Cookie and Windows Authentication. You will need to use the PolicyBuilder to enforce the 'require authentication' part.
On ConfigureServices method:
// add additional authorisation for cookie
services.AddAuthorization(options =>
{
options.AddPolicy("CookiePolicy", policy =>
{
policy.AddAuthenticationSchemes("NTLM", "MyCookie"); // order does matter. The last scheme specified here WILL become the default Identity when accessed from User.Identity
policy.RequireAuthenticatedUser();
});
});
On Configure method:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookie",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/AccessDenied/"),
AutomaticAuthenticate = false, // this will be handled by the authorisation policy
AutomaticChallenge = false // this will be handled by the authorisation policy
});
On Controller:
[Authorize("CookiePolicy")] // will check policy with the required authentication scheme (cookie in this case)
public IActionResult AuthorisedPageCookie()
{
return View();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.