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();
}
I try to add a user to a role like shown above. However it does not work because when trying to go to the following controller action:
[AuthorizeUser(Roles = RoleEnums.UserWithProfile)]
public ActionResult Index(Guid? userProfileId)
{
}
It fails to authorize. What is strange is that it successfully manages to authorize users added in the database seeding.
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);
}
}
What am I missing here? Is the method AddUserToRole() incorrect and why is only the seeding giving me correct behavior?
Edit: ASP.NET Identity check user roles is not working found this and it seems to be the problem here. But i don't want users to have to manually logout and in again. They mention something about updating the security stamp but that did not work for me.
Edit2: See my posted answer for the solution i ended up with.