简体   繁体   中英

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

Moved from ASP.NET Core 1.1 to 2.0 and having issues with cookie authentication.

The application will not follow the LoginPath and goes directly to the AccessDeniedPath .

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));
    });
}

This does not redirect to the login method at all. While testing I changed the AccessDeniedPath to point at the Login method, and it logs the user in fine.

Completely stumped as to why the LoginPath doesn't direct to the Login method.

Add [Authorize] to the controller(s) you wish to force redirect from.

eg

using Microsoft.AspNetCore.Authorization;

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

According to the documentation , the first you need in ConfigureServices is to add Identity. Something like:

services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    // Signin settings
    options.SignIn.RequireConfirmedEmail = true;
    options.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM