asp.net 为什么使用User.IsInRole()总是返回false?

fdbelqdn  于 2023-11-20  发布在  .NET
关注(0)|答案(3)|浏览(115)

我使用User.IsInRole()检查登录后,具有管理员角色的用户将直接进入管理页面,如果他们没有管理员角色,他们将进入另一个页面。但是,User.IsInRole()总是返回false

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

字符串
我想用它来检查登录后,具有admin角色的用户会立即转到admin页面

esyap4oy

esyap4oy1#

除了使用User.IsInRole(),您还可以使用UserManager来检查角色。

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

字符串

unftdfkk

unftdfkk2#

为什么使用User.IsInRole()总是返回false
当用户使用他们的用户名和密码进行身份验证并成功登录时,他们将获得一个令牌,包含可用于身份验证和授权的身份验证票据。令牌存储为cookie,随客户端发出的每个请求一起发送。Cookie身份验证中间件执行此cookie的生成和验证。中间件将用户主体序列化为加密cookie。在随后的请求,中间件验证cookie,重新创建主体,并将主体分配给User属性。
在您成功登录后(完成登录操作,而不是在当前登录后操作中),在后续请求中,您将在另一个Authorize操作中获得User.IsInRole()。这就是为什么使用User.IsInRole()总是返回false的原因。
我使用User.IsInRole()检查登录后,具有管理员角色的用户将直接进入管理页面,
您可以尝试使用UserManager.IsInRoleAsync(TUser, String) Method检查User角色,如:

if  (await userManager.IsInRoleAsync(appUser, "Administrator")||await userManager.IsInRoleAsync(appUser, "Admin"))
       {
           return RedirectToAction("Index", "Tours", new { area = "Admin" });
          
       }

字符串

vxbzzdmp

vxbzzdmp3#

是否将角色添加为声明?
这就是我在项目中使用的方式:

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

字符串

相关问题