Okay first I just want to say what I'm trying to do has turned out to be a real PITA. The issue I'm having is similar to the following posts:
ASP.NET Identity check user roles is not working
Updating user role using asp.net identity
public async Task<ActionResult> MyAccount()
{
var userId = User.Identity.GetUserId();
var user = await UserManager.FindByIdAsync(userId);
if (!User.IsInRole(RoleConst.EXPIRED))
{
await UserManager.AddToRoleAsync(userId, RoleConst.EXPIRED);
await SignInAsync(user, false);
}
var isExpired = User.IsInRole(RoleConst.EXPIRED); // FALSE!!
return View(model);
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}
The role does not update even after using the sign in method to refresh the cookie as some other users have suggested. Of course the role is updated in the db.
This code works when checking the role after updating:
var isExpired = UserManager.IsInRole(userId, RoleConst.EXPIRED);
I would be fine with that I guess, however, I need to do this check immediately after in my razor Views. I haven't found how I can use the UserManger outside of the controller. Any suggestions to this seemingly simple task would be appreciated!
EDIT
I've also tried the following which yields the same result:
await UserManager.AddToRoleAsync(user.Id, RoleConst.EXPIRED);
await UserManager.UpdateSecurityStampAsync(user.Id);
var isExpired = User.IsInRole(RoleConst.EXPIRED); // FALSE