MVC 5 AddToRole requires logout before it works?

后端 未结 4 688
后悔当初
后悔当初 2020-12-05 15:26

I\'m finding that if I add a user to a role in ASP Identity, it doesn\'t take effect until I log out and log back in. Is there something I need to do to refresh a user\'s ro

4条回答
  •  无人及你
    2020-12-05 16:25

    @kevin-junghans your answer lead me to the correct answer. This code shows how to add a user to a role in MVC 5 and to have that role automatically take effect.

    var userManager = new UserManager(new UserStore(new ApplicationDbContext()));
    var userId = HttpContext.Current.User.Identity.GetUserId();
    
    userManager.AddToRole(userId, roleName);
    
    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
    
    authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    
    var user = userManager.FindById(userId);
    var identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
    
    authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
    

提交回复
热议问题