关于 c#:ASP.NET Core 2.0 Cookie Authentication without identity notdirecting to LoginPath

ASP.NET Core 2.0 Cookie Authentication without identity not directing to LoginPath

从 ASP.NET Core 1.1 移至 2.0 并存在 cookie 身份验证问题。

应用程序不会跟随 LoginPath 并直接转到 AccessDeniedPath

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = new PathString("/Account/Login/");
            options.AccessDeniedPath = new PathString("/Account/Forbidden/");
        });

    services.AddAuthorization(options =>
    {
        options.AddPolicy(Constants.CONST_POLICY_SUPERADMIN, policy => policy.RequireRole(Constants.CONST_ROLE_SUPERADMIN));
        options.AddPolicy(Constants.CONST_POLICY_ADMIN, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN));
        options.AddPolicy(Constants.CONST_POLICY_DIR, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN, Constants.CONST_ROLE_DIR));
        options.AddPolicy(Constants.CONST_POLICY_HoD, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN, Constants.CONST_ROLE_DIR, Constants.CONST_ROLE_HoD));
        options.AddPolicy(Constants.CONST_POLICY_STAFF, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN, Constants.CONST_ROLE_DIR, Constants.CONST_ROLE_HoD, Constants.CONST_ROLE_STAFF));
    });
}

这根本不会重定向到登录方法。在测试时,我将 AccessDeniedPath 更改为指向 Login 方法,并且它可以很好地记录用户。

完全不知道为什么 LoginPath 不指向 Login 方法。


将 [Authorize] 添加到您希望从中强制重定向的控制器。

例如

1
2
3
4
5
using Microsoft.AspNetCore.Authorization;

 [Authorize]
public class HomeController : Controller
{ ....