nik
nik

Reputation: 1479

How to add and enable OWIN role to a logged in user?

I'm using MVC 5 with OWIN authentication. When adding a role to a signed in user it won't take effect until user relogs:

    [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 do make role changes take effect immediately?

Upvotes: 4

Views: 1170

Answers (1)

DavidEdwards
DavidEdwards

Reputation: 593

I believe that the AddUserToRole method does the assignment at the database level. While this probably needs to happen also, what you need to do is refresh the current identity.

Short answer: Cast the IPrincipal to a ClaimsPrincipal and cast the IIdentity to a ClaimsIdentity. Then you can just add the claim.

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

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

Upvotes: 1

Related Questions