【问题标题】:User.IsInRole return falseUser.IsInRole 返回 false
【发布时间】:2015-08-02 20:25:09
【问题描述】:

我在 mvc 5 网站中使用 Identity 2 进行身份验证。在我看来,我想检查用户的角色:

@if(User.IsInRole("Customers"))
{
  @*do something*@
}

但这总是返回 false,我已经在 web 配置中设置了 <roleManager enabled="true" />。 请帮忙。

【问题讨论】:

  • 您的数据库是否表明用户确实在角色中,并且角色名称是否完全正确?用户是否确实已登录? IE...如果您将[Authorize] 添加到控制器,操作会加载吗?
  • 角色的名字是正确的,它存在于该用户的数据库中。
  • 如果您将[Authorize(Roles = "Customers")] 添加到您的操作中,该操作会加载吗?您是如何将用户添加到角色的?
  • 不,它不会加载。角色添加到后端: ApplicationUser user = UserManager.FindById(userId); UserManager.AddToRole(user.Id, roleName);
  • 嗯很奇怪。我必须承认,在您发布此问题之前,我不知道这种方法存在。

标签: asp.net-mvc asp.net-identity roles


【解决方案1】:

我刚刚让它与我也使用身份框架的设置一起工作。

我使用以下代码将用户添加到角色:

this.RoleManager.CreateAsync(new Role() {Name  = "Customers"});

this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");

在那之后的任何时候,当我运行 User.IsInRole("Customers"); 时它返回 false,直到我重新登录它们。

将用户添加到角色后,您需要重新登录用户。角色信息存储在 cookie 中。

我运行以下命令再次记录用户:

var user = await this.UserManager.FindByNameAsync("bob");
var identity = await this.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

this.AuthManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);

从那时起,User.IsInRole("Customers") 为我工作并返回true。

除非您可以在应用程序中验证它是否知道您要将它们添加到的角色,否则这将不起作用。您可以通过以下方式使用 RoleManager 验证角色“客户”的存在:

var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);

【讨论】:

    【解决方案2】:

    我有同样的问题,因为我自定义了IdentityDbContext 类。在我的情况下,User.IsInRole("Customers") 总是错误的原因是因为我在自定义上下文类上关闭了 EF 延迟加载。我尝试打开延迟加载,然后注销然后登录,User.IsInRole 正在返回预期值。

    public partial class Context : IdentityDbContext<User>
        {
            public Context() : base("name=Context")
            {
                this.Configuration.LazyLoadingEnabled = true;          
            }
    

    【讨论】:

    • 首先我认为这是一个解决方案,但在我的情况下,故障不是确定性的。根据我的调试,LazyLoadingEnabled = true; 是默认值(MVC 5)
    【解决方案3】:

    对我来说,问题出在 Startup 类中,我没有像这样注册角色存储

    services.AddDefaultIdentity<ApplicationUser>() .AddEntityFrameworkStores<ApplicationDbContext>();

    所以只需添加.AddRoles&lt;IdentityRole&gt;(),它会为我解决问题

    services.AddDefaultIdentity<ApplicationUser>() .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();

    【讨论】:

      【解决方案4】:

      最近我在没有使用 SSL 的情况下运行应用程序时遇到了同样的问题,所以我的浏览器在启用 SSL 后拒绝运行应用程序的 cookie 解决了我的问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-15
        • 1970-01-01
        • 2019-08-14
        • 1970-01-01
        • 2018-07-14
        • 2016-07-29
        • 2018-12-11
        相关资源
        最近更新 更多