Asp.Net 多个 AuthenticationSchemas - 用户不会被重定向到 LoginPath Uri

Asp.Net multiple AuthenticationSchemas - User doesn't get redirected to LoginPath Uri

我正在尝试为 API 控制器设置一个 ASP.Net 5 网络项目 JWTBearer authentication(用 APIController 属性装饰的控制器)CookieAuthentication 用于 MVC 控制器 (控制器 类 从控制器派生,以呈现视图)Startup Class 中我的 ConfigureServices 方法的相关部分如下所示:

services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("My Secret Key")),
            ValidateAudience = false,
            ValidateIssuer = false,
            RequireExpirationTime = false,
            ValidateLifetime = true
        };
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.LoginPath = "/account/login";
        options.LogoutPath = "/account/logout";
        options.AccessDeniedPath = "/account/accessdenied";
        options.Cookie = new CookieBuilder {SameSite = SameSiteMode.Strict};
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
    });

var schemePolicy = new AuthorizationPolicyBuilder(
        CookieAuthenticationDefaults.AuthenticationScheme,
        JwtBearerDefaults.AuthenticationScheme)
    .RequireAuthenticatedUser()
    .Build();

services.AddAuthorization(o => o.DefaultPolicy = schemePolicy);

在 MCV 控制器中,我有一个 Action 如下所示:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult AnActionForAuthenticatedUsers()
{
    //  do some stuff...
    return View();
}

现在我希望当针对此操作的未经身份验证的请求进入时,请求将被转发到 /account/login,但事实并非如此。而是返回 401 statuscode

网络服务器说:

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed. These requirements were not met:
      DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
      AuthenticationScheme: Cookies was challenged.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
      AuthenticationScheme: Bearer was challenged.

我在这里错过了什么?

这里的问题不在Authentication policy,而是在Authorization配置 为每种类型的授权创建一个单独的策略,这将按您的预期工作:

services.AddAuthorization(o =>
{
    o.AddPolicy(CookieAuthenticationDefaults.AuthenticationScheme, schemePolicy);
    o.AddPolicy(JwtBearerDefaults.AuthenticationScheme, schemePolicy);
});