ASP.NET Core 2.0 - AddAuthentication和DefaultScheme

问题描述 投票:1回答:3

我正在尝试将ASP.NET Core 1.1应用程序升级到2.0。该应用程序需要两个基本身份验证和JWT一个。我有代码看起来像这样:

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

我的问题是,我似乎无法让他们两个同时工作!我设置为DefaultScheme的唯一一个是有效的,另一个是中断并返回HTTP 401。

任何想法我怎么能让他们两个工作?

c# asp.net asp.net-core asp.net-core-mvc asp.net-core-2.0
3个回答
2
投票

只是设法让这个工作...这个链接帮助:https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2

重要的是这里: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:


0
投票

您必须从AddAuthotization方法中删除选项:

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

然后修改您的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();
        });

现在,在GetSchemeForRequest方法中,您可以确定应该使用哪种方案。我找到答案here并应用于我的代码。有用!


0
投票

将这行代码添加到Startup.cs对我有用

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddCookie("LoggedIn");
© www.soinside.com 2019 - 2024. All rights reserved.