I use User.IsInRole() to check that after logging in, users with the admin role will go straight to the admin page, if they don’t have the admin role, they will go to another page. However, User.IsInRole() always returns false
enter image description here
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
UserManager<AppUser> usermanager;
if (User.IsInRole("Administrator")||User.IsInRole("Admin"))
{
return RedirectToAction("Index", "Tours", new { area = "Admin" });
}
else
{
return RedirectToPage(returnUrl);
}
I want to use it to check that after logging in, users with the admin role will immediately go to the admin page
3
Answers
When a user authenticates using their username and password,and successfully logged in, they’re issued a token, containing an authentication ticket that can be used for authentication and authorization. The token is stored as a cookie that’s sent with every request the client makes. Generating and validating this cookie is performed by the Cookie Authentication Middleware. The middleware serializes a user principal into an encrypted cookie. On subsequent requests, the middleware validates the cookie, recreates the principal, and assigns the principal to the
User
property.After you successfully logged in( Complete login action, not in the current login post action), on subsequent requests, you will get User.IsInRole() in another Authorize action.That’s the reason why using User.IsInRole() always return false.
You can try to use UserManager.IsInRoleAsync(TUser, String) Method to check the User role like:
Instead of using
User.IsInRole()
, you can also use theUserManager
to check roles.Are you adding your roles as claims?
This is how I am using in my projects: