在ASP.NET Core中使用多种身份验证方案

J.D*_*Doe 5 authentication asp.net-mvc basic-authentication bearer-token asp.net-core

我已经使用ASP.NET Core开发了Web API,并且需要能够对同一服务使用基本身份验证和承载身份验证方案。由于某种原因,它不起作用:它始终将呼叫视为承载者。这是我的代码:

这是我在控制器中拥有的属性:

[Authorize(ActiveAuthenticationSchemes = "Basic,Bearer")]
[ResponseCache(NoStore = true, Duration = 0, VaryByHeader = "Authorization")]
Run Code Online (Sandbox Code Playgroud)

这是我的startup.cs:

这部分是针对基本身份验证的:

   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);
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

和这段用于承载身份验证的代码:

    app.UseAPIKeyAuthentication(new BearerApiKeyOptions
        {
            AuthenticationScheme = BearerApiKeySchema,
            AutomaticAuthenticate = false  
        });     
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以从官方 Microsoft GitHub 中查看此内容以获取一些参考。

我的用例略有不同,我需要 Cookie 和 Windows 身份验证的组合。您将需要使用 PolicyBuilder 来强制执行“需要身份验证”部分。

在 ConfigureServices 方法上:

            // 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();
                });
            });
Run Code Online (Sandbox Code Playgroud)

在配置方法上:

            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
            });
Run Code Online (Sandbox Code Playgroud)

在控制器上:

        [Authorize("CookiePolicy")] // will check policy with the required authentication scheme (cookie in this case)
        public IActionResult AuthorisedPageCookie()
        {
            return View();
        }
Run Code Online (Sandbox Code Playgroud)