Ale*_*sko 11 asp.net-mvc-5 asp.net-identity
我发现如果我将用户添加到ASP身份中的角色,它会在我退出并重新登录之后才会生效.我是否需要做一些事情来刷新用户的角色而不强迫用户登录先关掉?
以下是我将用户添加到角色的方式.
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var userId = HttpContext.Current.User.Identity.GetUserId();
userManager.AddToRole(userId, roleName);
Run Code Online (Sandbox Code Playgroud)
然后,几乎立即,我将用户重定向到此操作方法.我可以在数据库中告诉我已经添加到正确的角色,但MVC仍然将我重定向到登录页面.但是,如果我退出,重新登录,并尝试转到此操作方法,它可以正常工作.
[Authorize(Roles = RecoveryStandardRoles.ServiceProvider)]
public partial class CertifyController : Controller
{
#region Public Methods and Operators
public virtual ActionResult CompanyProfile()
{
return this.View();
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
感谢您花时间看我的问题!
小智 8
MVC5注册新用户,分配角色并激活具有角色的用户,无需注销并重新使用:await UserManager.AddToRoleAsync(user.Id,"Role Name")
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email,StandName = model.StandName,FirstName = model.FirstName,LastName = model.LastName,CellPhone = model.CellPhone,Supervisor = model.Supervisor};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
if (result.Succeeded)
{
***await UserManager.AddToRoleAsync(user.Id, "Users Tammy");***
await SignInAsync(user, isPersistent: false);
Run Code Online (Sandbox Code Playgroud)
@ kevin-junghans你的回答引导我得到正确的答案.此代码显示如何将用户添加到MVC 5中的角色并使该角色自动生效.
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(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);
Run Code Online (Sandbox Code Playgroud)
ASP.NET Identity使用声明来存储角色并使用声明,而不是在每次需要执行授权时执行数据库查询.因此,在此人再次登录之前,角色不会出现在声明中.您可以在此处阅读有关在ASP.NET Identity中使用声明的信息.这些文章介绍了如何在登录过程中添加声明.但是,如果您向当前用户添加角色,则可以使用我对此QA的回答中描述的方法更新声明,而不必强制用户再次登录.分配给用户的每个角色都有一个声明.添加新角色时使用ClaimTypes.Role.
| 归档时间: |
|
| 查看次数: |
7717 次 |
| 最近记录: |