Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple authentication schemes in ASP.NET Core

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  
        });     
like image 570
J.Doe Avatar asked May 05 '17 09:05

J.Doe


People also ask

What is authentication scheme in ASP NET Core?

For an introduction to authentication schemes in ASP.NET Core, see Authentication scheme. In some scenarios, such as Single Page Applications (SPAs), it's common to use multiple authentication methods. For example, the app may use cookie-based authentication to log in and JWT bearer authentication for JavaScript requests.

How do I enable multiple authorization in ASP NET Core?

ASP.NET Core: Supporting multiple Authorization 1 Authenticating using Azure AD. To test our authentication on ‘api/users’ we need a valid Bearer token. ... 2 Using a custom Authorization Filter. ... 3 Adding a custom authentication scheme. ... 4 Dynamically applying an Authorization method at runtime. ... 5 Wrapping up. ...

Can I use multiple authentication methods for single page applications?

In some scenarios, such as Single Page Applications (SPAs), it's common to use multiple authentication methods. For example, the app may use cookie-based authentication to log in and JWT bearer authentication for JavaScript requests.

Can I support multiple authentication methods within the same WebAPI?

Every once in a while, you get the requirement to support multiple ways of authenticating within one application. This article covers the rare case of supporting two authentication providers from within the same ASP.NET Core WebAPI.


1 Answers

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();
        }
like image 156
ronnypm Avatar answered Oct 14 '22 00:10

ronnypm