asp.net-mvc - 如何在 ASP.NET MVC 5 中更改和应用当前用户的角色
问题描述
我将首先介绍导致我遇到角色授权问题的步骤。
首先,我在我的委托人中添加 2 个角色HomeController.cs
public HomeController()
{
_db = new ApplicationDbContext();
_roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_db));
_userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(_db));
List<string> roles = new List<string>()
{
"User", "Admin"
};
foreach(string role in roles)
{
if (!_roleManager.RoleExists(role))
{
_roleManager.Create(new IdentityRole(role));
}
}
}
角色已成功添加到数据库中。
然后我在注册任务中将角色添加到新注册用户AccountController.cs
...
if (result.Succeeded)
{
await UserManager.AddToRoleAsync(user.Id, "User");
...
角色User
已成功分配给新用户(在表中AspNetUserRoles
:)
然后,如果我将此用户角色更改为Admin
这样:
string userId = User.Identity.GetUserId<string>();
_userManager.RemoveFromRole(userId, "User");
_userManager.AddToRole(userId, "Admin");
并像这样在我的视图(Razor)中检查它:
@if(User.IsInRole("Admin"))
{
<p> ok </p>
}
并通过在我的 HomeController 中检查它[Authorize(Roles = "Admin")]
。
然后它失败了两次。if(User.IsInRole("Admin"))
返回 false 并且[Authorize(Roles = "Admin")]
也不允许我访问它下面的方法。
此外,这个新注册的用户只是User
角色,因为[Authorize(Roles = "User")]
工作并且if(User.IsInRole("User"))
也返回 true。
奇怪的是IList<string> roles
:
string userId = User.Identity.GetUserId<string>();
IList<string> roles = _userManager.GetRoles(userId);
实际上,当通过添加新角色时正确返回新角色列表,_userManager.AddToRole(userId, "Admin");
因此具有默认角色User
的用户现在只有 1 个角色Admin
(因为我删除了以前的角色),这看起来很合逻辑并且有效。
如果您知道为什么我的默认角色User
不能按照上面的方式更改,请发布您的答案,谢谢。
解决方案
要应用用户角色替换的更改,该用户应重新登录。基本上假设我们有一些服务叫做UserService
public class UserService
{
private ApplicationDbContext _db;
private ApplicationUserManager _userManager;
private ApplicationSignInManager _signInManager;
public UserService()
{
_db = new ApplicationDbContext();
_userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(_db));
IOwinContext owinContext = HttpContext.Current.GetOwinContext();
_signInManager = new ApplicationSignInManager(_userManager, owinContext.Authentication);
}
public async Task SaveRole()
{
ApplicationUser user = _userManager.FindById(HttpContext.Current.User.Identity.GetUserId());
await _signInManager.SignInAsync(user, true, true);
}
}
为用户分配角色后,我们需要调用SaveRole()
Task 来更新身份验证 cookie 以与数据库保持同步。
public class HomeController : Controller
{
private UserService _userService;
public HomeController()
{
_userService = new UserService();
}
public async Task<ActionResult> ApplyRole()
{
await _userService.SaveRole();
return RedirectToAction("JustTestRole", "Home");
}
}
ApplyRole
现在例如在视图 (.cshtml) 中调用Task:
<li>@Html.ActionLink("Apply role", "ApplyRole", "Home")</li>
当前用户角色已应用并准备好进行测试。例如:
[Authorize(Roles = "Admin")]
public ActionResult JustTestRole()
{
// to access this action user must have Admin role
}
推荐阅读
- android - Android Work Manager:我可以强制修剪已完成的作业吗?
- kotlin - 将 Completable 转换为 Single 的规范方法?
- python - ex 9.4 python coursera
- java - 比较器正在从树形图中删除重复的对象
- android - 从布尔数组获取/获取数据 - Firestore Android
- scala - Scala sortBy缺少扩展函数的参数类型
- javascript - ACE 编辑器:如何将更改的数据移动到 $_POST 或 $_GET
- c - 是否要求指向两个不同本地空对象的指针比较不相等?
- google-cloud-ml - Google 的 mlengine 环境是否可以作为图像下载?
- styles - 如何启用 Sharepoint 2013 富文本编辑器功能区表格样式?