简体   繁体   中英

ASP.NET Core 2.0 - AddAuthentication and DefaultScheme

I'm trying to upgrade an ASP.NET Core 1.1 application to 2.0. The application needs two both the basic authentication and JWT one. I have got code which looks something like this:

services.AddAuthentication(options =>
                    {
                        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                .AddBasic(BasicScheme, _ => { })
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {...}

My problem is that I can't seem to get both of them to work at the same time! Whichever one I set as the DefaultScheme is the only one that works and the other one breaks and returns a HTTP 401.

Any ideas how can I get both of them to work?

Just managed to get this to work... this link helped: https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2

The important bit is here:

When we use the Authorize attribute, it actually binds to the first authentication system by default. The trick is to change the attribute to specify which auth to use:

You have to remove option from AddAuthotization method:

services.AddAuthentication()
            .AddBasic(BasicScheme, _ => { })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {...}

Then modify your Configure() method Startup.cs adding the following Use instructions:

app.Use(async (context, next) =>
        {
            // Write some code that determines the scheme based on the incoming request
            string scheme = GetSchemeForRequest(context);
            var result = await context.AuthenticateAsync(scheme);
            if (result.Succeeded)
            {
                context.User = result.Principal;

            }
            await next();
        });

Now in the GetSchemeForRequest method you can determine which scheme you should use. I found the answer here and applied on my code. It works!

Adding this line of code to Startup.cs worked for me

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddCookie("LoggedIn");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM