skip to Main Content

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


  1. Why does using User.IsInRole() always return false

    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.

    I use User.IsInRole() to check that after logging in, users with the
    admin role will go straight to the admin page,

    You can try to use UserManager.IsInRoleAsync(TUser, String) Method to check the User role like:

    if  (await userManager.IsInRoleAsync(appUser, "Administrator")||await userManager.IsInRoleAsync(appUser, "Admin"))
           {
               return RedirectToAction("Index", "Tours", new { area = "Admin" });
              
           }
    
    Login or Signup to reply.
  2. Instead of using User.IsInRole(), you can also use the UserManager to check roles.

    var user = await _userManager.GetUserAsync(User);
    if (user != null)
    {
        var isAdmin = await _userManager.IsInRoleAsync(user, "Administrator") || await _userManager.IsInRoleAsync(user, "Admin");
        if (isAdmin)
        {
            return RedirectToAction("Index", "Tours", new { area = "Admin" });
        }
        else
        {
            return RedirectToPage(returnUrl);
        }
    }
    
    Login or Signup to reply.
  3. Are you adding your roles as claims?

    This is how I am using in my projects:

    // set default claims
    var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Email, user.Username),
            new Claim(ClaimTypes.Name, user.Name),
            new Claim(CustomClaimTypes.UserId, user._id.ToString())
        };
    
    // set user role claims
    foreach (var roleName in user.Roles)
    {
        Claim roleClaim = new Claim(ClaimTypes.Role, roleName);
        claims.Add(roleClaim);
    }
    
    var claimsIdentity = new ClaimsIdentity(
        claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
    var authProperties = new AuthenticationProperties
    {
        //AllowRefresh = <bool>,
        // Refreshing the authentication session should be allowed.
    
        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(120),
        // The time at which the authentication ticket expires. A 
        // value set here overrides the ExpireTimeSpan option of 
        // CookieAuthenticationOptions set with AddCookie.
    
        IsPersistent = Input.RememberMe,
        // Whether the authentication session is persisted across 
        // multiple requests. Required when setting the 
        // ExpireTimeSpan option of CookieAuthenticationOptions 
        // set with AddCookie. Also required when setting 
        // ExpiresUtc.
    
        IssuedUtc = DateTimeOffset.UtcNow,
        // The time at which the authentication ticket was issued.
    
        //RedirectUri = <string>
        // The full path or absolute URI to be used as an http 
        // redirect response value.
    };
    
    await HttpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,
        new ClaimsPrincipal(claimsIdentity),
        authProperties);    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search