tqrecords
tqrecords

Reputation: 542

AddToRole not updating User role

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

Upvotes: 0

Views: 1663

Answers (2)

Yuvifan
Yuvifan

Reputation: 67

It will work once you Sign out and signing in again (which is not a user-friendly option)

So try this (reordered these lines),

    await this.UserManager.AddToRoleAsync(user.Id, model.UserRole);
    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); 

So that the cookies get stored only after the user role gets added. :)

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239420

One person in the linked questions suggested signing out and signing in again, which you aren't even doing: just signing in. However, in one of the comments you can find a link to the answer you need. Long and short you need to call:

UserManager.UpdateSecurityStampAsync(userId);

After changing the user's roles.

Upvotes: 0

Related Questions