简体   繁体   中英

ASP.NET identity Multiple Login

I am trying to implement a administrator login page (Roles = "Admin"), but it seems like the authentication of ASP.NET Identity has only one authentication Cookies. I really want to implement 2 distinct login pages one for Admin Group and other for User group. Any suggestions or help?

 app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieName = "_user",

            CookiePath = "/",
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            LogoutPath = new PathString("/Account/Logoff"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account. 
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieName = "_admin",
            CookiePath = "/Admin",
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Admin/Home/Login"),
            //LogoutPath = new PathString("/Account/Logoff"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account. 
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

Login Controller:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                {
                    var user = new ClaimsPrincipal(AuthenticationManager.AuthenticationResponseGrant.Identity);

                    if (user.IsInRole("Admin"))
                    {

                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return View("Login");
                    }
                }
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

As @Jonathan Alfaro said. You don't need two cookies, you need to protect your admin resources(Action or Controller) using Authorize attribute. For example:

[Authorize(Roles = "Admin")]
public ActionResult AdminOnly()
{
    return View();
}

This action is available for users who have Admin role.

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