【发布时间】:2017-05-16 16:07:04
【问题描述】:
public void AddUserToRole(Guid userId, string roleName)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(DbContext));
var user = userManager.FindById(userId.ToString());
userManager.AddToRole(user.Id, roleName);
DbContext.SaveChanges();
}
我尝试将用户添加到如上所示的角色。但是它不起作用,因为在尝试执行以下控制器操作时:
[AuthorizeUser(Roles = RoleEnums.UserWithProfile)]
public ActionResult Index(Guid? userProfileId)
{
}
授权失败。奇怪的是,它成功地授权了数据库种子中添加的用户。
private void SeedUserRoles(List<ApplicationUser> applicationUsers, DbContext dbContext)
{
var userStore = new UserStore<ApplicationUser>(dbContext);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(applicationUsers[0].Id, RoleEnums.UserWithProfile);
userManager.AddToRole(applicationUsers[1].Id, RoleEnums.UserWithProfile);
userManager.AddToRole(applicationUsers[2].Id, RoleEnums.UserWithProfile);
userManager.AddToRole(applicationUsers[3].Id, RoleEnums.User);
}
private void CreateRoles(DbContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
if (!roleManager.RoleExists(RoleEnums.Admin))
{
var role = new IdentityRole { Name = RoleEnums.Admin };
roleManager.Create(role);
}
if (!roleManager.RoleExists(RoleEnums.User))
{
var role = new IdentityRole { Name = RoleEnums.User };
roleManager.Create(role);
}
if (!roleManager.RoleExists(RoleEnums.UserWithProfile))
{
var role = new IdentityRole { Name = RoleEnums.UserWithProfile };
roleManager.Create(role);
}
}
我在这里缺少什么? AddUserToRole() 方法是否不正确,为什么只有播种才能给我正确的行为?
编辑:ASP.NET Identity check user roles is not working 找到了这个,这似乎是这里的问题。但我不希望用户必须手动注销并再次登录。他们提到了一些关于更新安全标记的事情,但这对我不起作用。
Edit2:查看我发布的答案以了解我最终得到的解决方案。
【问题讨论】:
-
如果您收到授权错误,您确定使用正确的用户添加角色吗?它应该是角色 = RoleEnums.UserWithProfile.. 的用户。数据库播种有效,因为它没有授权限制,而操作方法有身份验证限制(请参阅过滤器)
-
令我印象深刻的是,在 AddUserToRole() 方法中,您使用字符串作为参数,而播种方法使用 RoleEnums 类的静态属性。您在调用 AddUserToRole() 时用作角色的字符串是否可能与 RoleEnums.UserWithProfile 不匹配?
标签: c# asp.net entity-framework asp.net-identity