简体   繁体   中英

Asp.net Identity: change user role while logged in

I have a page where a logged-in user performs an action and based on that I change the user's role like this:

    var userStore = new UserStore<IdentityUser>();
    var manager = new UserManager<IdentityUser>(userStore);

    IdentityUser user = manager.FindById(TheMembershipID);

    manager.RemoveFromRole(user.Id, "StartUser");
    manager.AddToRole(user.Id, "AppUser");

Then, on the client, there's a redirect to another page that requires authentication in the AppUser role. The problem is that the user shows as being still logged in as a StartUser.

How do I change the role of a user while he's logged in?

You need to log them out and back in for the new role to take effect. After your code:

//Get the authentication manager
var authenticationManager = HttpContext.GetOwinContext().Authentication;

//Log the user out
authenticationManager.SignOut();

//Log the user back in
var identity = manager.CreateIdentity(user,DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { IsPersistent = true}, identity);

This isn't exact, but should give you the general idea.

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