【问题标题】:ASP.NET Identity and User.IsInRoleASP.NET 身份和 User.IsInRole
【发布时间】:2017-04-28 20:05:26
【问题描述】:

我将项目从 Membership provider 转移到 ASP.NET Identity,我添加了以下角色管理器:

public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(RoleStore<ApplicationRole> store)
                : base(store)
    { }
    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,
                                            IOwinContext context)
    {
        return new ApplicationRoleManager(new
                RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}

我尝试将用户添加到角色:

        await UserManager.AddClaimAsync("46bf12b9-6b9e-43f9-ad9b-8fff27987978", claim: new Claim(ClaimTypes.Role.ToString(), "Admin"));

记录已添加,但 User.IsInRole 不起作用。为什么以及如何解决?

【问题讨论】:

    标签: asp.net-core claims-based-identity asp.net-identity-2


    【解决方案1】:

    声明和角色不同,请参阅herehere。您应该使用AddToRoleAsync 中包含的方法UserManager&lt;T&gt;。这是一个例子。

    var user = new ApplicationUser
    {
        Username = "Rob@Microsoft.com",
        Email = "Rob@Microsoft.com"
    };
    
    var result = await _userManager.CreateAsync(user, "P@ssw0rd");
    if (result.Succeeded)
    {
        await _userManager.AddToRoleAsync(user, "Admin");
    }
    

    【讨论】:

      【解决方案2】:

      最好使用AddToRoleAsync 方法——它做的事情非常相似,你不必自己做。此外,如果内部实现发生变化,您无需更新代码。

      至于User.IsInRole 不起作用 - 我怀疑它在您通话后不会立即起作用。但是,如果您将用户注销并重新登录,您将看到角色就位。这是因为User.IsInRole 会检查cookie,而AddClaimAsync 会将声明添加到数据库中。并且 cookie 不会在每次调用时从 DB 中刷新,因此在查看 cookie 时您不会在 DB 中看到新添加的信息。有办法强制这样做,但这超出了这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-11
        • 1970-01-01
        • 2011-10-30
        • 2014-01-21
        • 2013-11-10
        • 1970-01-01
        • 1970-01-01
        • 2020-11-17
        相关资源
        最近更新 更多