未击中身份验证处理程序(.NET Core 2.1 MVC)

时间:2018-10-11 15:48:25

标签: asp.net-mvc authentication asp.net-core

我的应用程序在启动时配置了多个身份验证处理程序:

services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })                
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                ...
            })
            .AddApiKeyAuth();  

openid connect auth工作正常,但是我希望一个特定的控制器使用我定义的“ ApiKeyAuth”。因此,根据文档:

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-2.1&tabs=aspnetcore2x

我指定了我希望该控制器使用的身份验证方案:

[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = ApiKeyAuthHandler.SchemeName)]
public class MyApiController : ControllerBase

但是,该应用似乎只是忽略了这一点,而openId连接处理程序似乎正在启动。

我缺少了什么,为什么忽略了我的属性?

1 个答案:

答案 0 :(得分:1)

好的,我发现使用全局身份验证策略是导致此问题的原因。我删除了以下几行,并向所有控制器手动添加了Auth属性(同时仅在其他控制器上指定了备用auth方案),现在它的行为如我所愿。

services.AddMvc(config =>
        {
            Remove--> var policy = new AuthorizationPolicyBuilder()
                 .RequireAuthenticatedUser()
                 .Build();

            Remove --> config.Filters.Add(new AuthorizeFilter(policy));
        });
相关问题