Asp.net 身份:登录时更改用户角色
本文关键字:用户 角色 登录 net 身份 Asp | 更新日期: 2023-09-27 18:35:07
我有一个页面,登录用户在其中执行操作,并在此基础上更改用户的角色,如下所示:
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");
然后,在客户端上,重定向到另一个页面,该页面需要在 AppUser 角色中进行身份验证。问题是用户显示为仍以启动用户身份登录。
如何在用户登录时更改用户的角色?
您需要注销
并重新登录才能使新角色生效。 在代码之后:
//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);
这并不准确,但应该给你一个大致的想法。