Refresh current user's role when changed in ASP.NET identity framework?
Asked Answered
D

2

16

Using VS 2013, standard MVC template, and the Identity provider framework

The user is logged in, and I have:

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

And the Members controller is as follows:

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

After Line X is executed, I can confirm that the user is added to the table dbo.AspNetUserRoles. However, the user upon reaching the Members controller fails the role check. User.IsInRole("Members") returns false.

If the user logs off and then logs in again, then access to the Members controller will go through, ie User.IsInRole("Members") now returns true.

Is there some caching? Why the delay? How do I overcome it?

I also tried converting the method at Line X to an async method and used UserManager.AddToRoleAsync. The same delayed effect is still there.

Darlinedarling answered 26/3, 2015 at 17:47 Comment(0)
L
30

The identity information(roles,claims) are put into the cookie when the user logs in. Since the user is already logged in, this line of code UserManager.AddToRole(User.Identity.GetUserId(), "Members") will update the db , but not the cookie. You have to have to re-issue the cookie.

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

Legislative answered 26/3, 2015 at 18:38 Comment(3)
This should actually be something that should be explained for the Role.AddUserToRole() method. Or a "Caution!" box in the documentation.Erysipelas
1 question: Mostly roles are assigned by someone else, is there an easy way using Identity to sent a sort of notification to the user to refresh his cookie?Rodolphe
If We need to implement a role based subscription in our site ( ie..user purchase a subscription we need to show extra presages without login) this will use full @CularBytes.Tertian
A
0

There is a problem with the @tmg's accepted answer.

SignInManager.SignInAsync(user) only updates cookies of the user who assigns a role, not the user assigned to a role.

If you want cookies of that user to be updated, you must somehow achieve to make SignInAsync command executed by that user. Like placing the command to the home page.

No need to say this is not a definite solution.

Apportionment answered 13/12, 2023 at 8:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.