Refresh current user role upon change in ASP.NET authentication system?

Using VS 2013, the standard MVC pattern and identity provider infrastructure

The user is logged in and I have:

//.... UserManager.AddToRole(User.Identity.GetUserId(), "Members"); # Line X RedirectToAction("Index", "Members"); 

And the member controller is as follows:

 [Authorize(Roles="Members")] public class MembersController : Controller { // GET: Members public ActionResult Index() { return View(); } } 

After running line X, I can confirm that the user has been added to the dbo.AspNetUserRoles table. However, the user does not check the role when it reaches the Member controller. User.IsInRole("Members") returns false.

If the user logs out and then logs back in, then access to the member controller will pass, i.e. User.IsInRole("Members") now returns true.

Is there any caching? Why is the delay? How to overcome it?

I also tried to convert the method in Line X to async method and used UserManager.AddToRoleAsync . The same deferred effect still exists.

+8
asp.net-mvc asp.net-identity roleprovider
source share
1 answer

Information about the identity (role, claim) is placed in the cookie when the user logs in. Since the user is already registered, this line of code UserManager.AddToRole(User.Identity.GetUserId(), "Members") update the db, but not the cookie. You will need to resend the cookie.

Try adding SignInManager.SignIn(user, false, false); (if you do not have a user, var user = UserManager.FindById(User.Identity.GetUserId()) ) before RedirectToAction("Index", "Members");

+16
source share

All Articles