Using multiple authentication schemes in ASP.NET Core
asp.net-core, asp.net-mvc, authentication, basic-authentication, bearer-token
Solution
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();
}
Problem
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 }); ```