How to add and enable the OWIN role for a registered user?

I am using MVC 5 with OWIN authentication. When a role is added to a subscribed user, it does not take effect until the user restarts the user:

    [Authorize(Roles = "Role1")]
    public async Task<ActionResult> Action()
    {
        var currentUser = AuthenticationManager.User;
        var currentUserId = currentUser.Identity.GetUserId();
        var result = await UserManager.AddToRoleAsync(currentUserId, "Role2"); //result confirms role added 

        return RedirectToAction("AnotherAction", "Controller");
    }

    // not accessible until relog
    [Authorize(Roles = "Role2")]
    public ActionResult AnotherAction()
    {
        return View();
    }

How to make role changes take effect immediately?

+4
source share
1 answer

I believe the AddUserToRole method does the job at the database level. Although this is likely to happen as well, what you need to do is update your current identity.

Short answer: translate IPrincipal to ClaimsPrincipal and pass the IIdentity value to ClaimsIdentity. Then you can simply add a request.

 ClaimsPrincipal currentPrincipal = (ClaimsPrincipal)this.User;
 ClaimsIdentity currentIdentity = (ClaimsIdentity)currentPrincipal.Identity;

 currentIdentity.AddClaim(new Claim(ClaimTypes.Role, "Role2"));
+1

All Articles