Multiple Login Page with Identity Core and Asp.net Core 3.1

Viewed 793

I Have an Asp.net Core Application with 2 areas, each area has its own login page. I use this code to redirect the user to the login page :

  services.AddAuthentication(opt => { opt.DefaultScheme = "AdminAuth";})
                    .AddCookie("UserAuth", opt => { opt.LoginPath = "/User/Login"; opt.AccessDeniedPath = "/User/AccessDenied";  })
                    .AddCookie("AdminAuth", opt => { opt.LoginPath = "/Identity/Account/Login"; opt.AccessDeniedPath = "/Admin/Dashboard/AccessDenied"; });

after submitting the login form, the user login successfully but didn't go to the controller and come back to the login page. I Use these attributes for controllers : for Admin :

[Authorize(Roles = "Admin", AuthenticationSchemes = "AdminAuth")]

for Users :

 [Authorize(Roles = "User", AuthenticationSchemes = "UserAuth")]

and for login, I am using this code :

_signInManager.PasswordSignInAsync(model.Username, model.Password, false, lockoutOnFailure: false);
1 Answers

Identity encapsulates the basic cookie authentication method. But identity does not provide cookie settings corresponding to the scheme.

I suggest you use cookie authentication, and add cookies to the specified scheme. Or one of the businesses uses basic cookie authentication. While another business uses identity.

Please make sure to indicate these schemas when use HttpContext.SignInAsync("schema",claimsPrincipal). Otherwise, it will only generate the default schema's cookie which you configure in startup.

This is an example of user login.

    public IActionResult login()
    {
        string username = "username";
        string userpassword = "password";
        var userClaim = new List<Claim>
            {
                new Claim(ClaimTypes.Name,username),
                new Claim(ClaimTypes.Role,"User")
            };
        var personIdentity = new ClaimsIdentity(userClaim, "identitycard");
        var principle = new ClaimsPrincipal(new[] { personIdentity });

        HttpContext.SignInAsync("UserAuth", principle);
        return Redirect("resource");
    }

Then, two cookies will be written to the browser.

enter image description here

Related