我在 mvc 5 网站中使用 Identity 2 进行身份验证。在我看来,我想检查用户的角色:
@if(User.IsInRole("Customers"))
{
@*do something*@
}
但这总是返回 false,我已经在网络配置中设置了
<roleManager enabled="true" />
。
请帮忙。
我刚刚让它与我的设置一起使用,该设置也使用身份框架。
我使用以下代码将用户添加到角色:
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 来验证角色“Customers”是否存在:
var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);
对我来说,问题出在启动类中,我没有像这样注册角色存储
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
所以只需添加
.AddRoles<IdentityRole>()
,它就会为我解决问题
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
自从我自定义了
IdentityDbContext
类以来,我也遇到了同样的问题。在我的例子中, User.IsInRole("Customers")
始终为 false 的原因是因为我在自定义上下文类上关闭了 EF 延迟加载。我尝试打开延迟加载,然后注销然后登录,并且 User.IsInRole
返回预期值。
public partial class Context : IdentityDbContext<User>
{
public Context() : base("name=Context")
{
this.Configuration.LazyLoadingEnabled = true;
}
最近我遇到了同样的问题,我在没有 SSL 的情况下运行应用程序,因此在启用 SSL 后我的浏览器拒绝运行应用程序的 cookie,这为我解决了这个问题
我尝试了上述所有解决方案,但没有任何效果。但后来我在 Program.cs (ASP.NET Core 6) 中添加了这行代码,然后注销并再次登录,瞧......它成功了。希望这有帮助!
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>();