【问题标题】:AddToRole not updating User roleAddToRole 不更新用户角色
【发布时间】:2016-02-11 19:10:56
【问题描述】:

好吧,首先我只想说我想做的事竟然是一个真正的 PITA。我遇到的问题类似于以下帖子:

ASP.NET Identity check user roles is not working

Updating user role using asp.net identity

public async Task<ActionResult> MyAccount()
{
   var userId = User.Identity.GetUserId();
   var user = await UserManager.FindByIdAsync(userId);

    if (!User.IsInRole(RoleConst.EXPIRED))
    {
        await UserManager.AddToRoleAsync(userId, RoleConst.EXPIRED);
        await SignInAsync(user, false);
    }
    var isExpired = User.IsInRole(RoleConst.EXPIRED); // FALSE!!

    return View(model);
}

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    var authenticationManager = HttpContext.GetOwinContext().Authentication;
    authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
    authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}

按照其他用户的建议,即使在使用登录方法刷新 cookie 后,角色也不会更新。当然角色在数据库中更新。

此代码在更新后检查角色时有效:

var isExpired = UserManager.IsInRole(userId, RoleConst.EXPIRED);

我想我会很好,但是,我需要在我的剃刀视图中立即进行此检查。我还没有找到如何在控制器之外使用 UserManger。对这个看似简单的任务的任何建议将不胜感激!

编辑

我还尝试了以下产生相同结果的方法:

 await UserManager.AddToRoleAsync(user.Id, RoleConst.EXPIRED);
 await UserManager.UpdateSecurityStampAsync(user.Id);
 var isExpired = User.IsInRole(RoleConst.EXPIRED); // FALSE

【问题讨论】:

    标签: asp.net-mvc razor identity


    【解决方案1】:

    链接问题中的一个人建议退出并重新登录,而您甚至没有这样做:只是登录。但是,在其中一个 cmets 中,您可以找到 link to the answer you need。长短需要调用:

    UserManager.UpdateSecurityStampAsync(userId);
    

    更改用户角色后。

    【讨论】:

    • 这个也试过了,使用代码的时候还是看不到角色:User.IsInRole(RoleConst.EXPIRED)
    • 我还可以确认数据库中的安全标记正在更新。
    【解决方案2】:

    一旦您退出并再次登录,它就会起作用(这不是一个用户友好的选项)

    所以试试这个(重新排序这些行),

        await this.UserManager.AddToRoleAsync(user.Id, model.UserRole);
        await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); 
    

    只有在添加用户角色后才存储 cookie。 :)

    【讨论】:

    • 不知道为什么再次调用 SignInManager 会成功,但我会接受的!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多