在我的aspnet core MVC应用程序中,如果我使用注入的UserManager检索用户,那么下面的代码将返回true
await _userManager.IsInRoleAsync( user, "Administrator" );但是,每当我在这样的视图中检查User (ClaimsPrincipal)时,就会丢失声明(返回false):
User.IsInRole( "Administrator" );对我来说,这似乎不一致。
我必须自己手动设置角色声明吗?我认为这将是免费的,并且自定义的UserClaimsPrincipalFactory将用于特定于应用程序的声明,而不是角色(使用MVC即可使用)。
我遗漏了什么?
发布于 2019-01-16 17:49:46
这是2.1版本中的一个已知问题,并已在2.2预览版-1中修复。
在asp.net核心2.1中,使用了AddDefaultIdentity,注入变成了
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>(),不会在默认情况下启用Roles,并且对于User.IsInRole,它始终返回false。
为了绕过它,不使用新的AddDefaultIdentity<TUser>()来配置身份,只需使用旧式的api:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();另一种方法是,您可以将UserClaimsPrincipal工厂替换为ConfigureService中代码下面的角色aware.Add的工厂,并引用UserRoles in DefaultIdentity
services.AddScoped<IUserClaimsPrincipalFactory<IdentityUser>, UserClaimsPrincipalFactory<IdentityUser, IdentityRole>>();https://stackoverflow.com/questions/54205520
复制相似问题