简体   繁体   English

ASP.NET Core 2.0 - AddAuthentication 和 DefaultScheme

[英]ASP.NET Core 2.0 - AddAuthentication and DefaultScheme

I'm trying to upgrade an ASP.NET Core 1.1 application to 2.0.我正在尝试将 ASP.NET Core 1.1 应用程序升级到 2.0。 The application needs two both the basic authentication and JWT one.应用程序需要两种基本身份验证和 JWT 一种。 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.我设置为 DefaultScheme 的任何一个都是唯一有效的,而另一个中断并返回 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刚刚设法让它工作......这个链接有帮助: 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.当我们使用 Authorize 属性时,它实际上默认绑定到第一个身份验证系统。 The trick is to change the attribute to specify which auth to use:诀窍是更改属性以指定要使用的身份验证:

You have to remove option from AddAuthotization method:您必须从 AddAuthotization 方法中删除选项:

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

Then modify your Configure() method Startup.cs adding the following Use instructions:然后修改您的 Configure() 方法 Startup.cs 添加以下使用说明:

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.现在在 GetSchemeForRequest 方法中,您可以确定应该使用哪种方案。 I found the answer here and applied on my code.我在这里找到了答案并应用于我的代码。 It works!它有效!

Adding this line of code to Startup.cs worked for me将这行代码添加到 Startup.cs 对我有用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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