简体   繁体   中英

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?

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM