0

我将首先介绍导致我遇到角色授权问题的步骤。

首先,我在我的委托人中添加 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不能按照上面的方式更改,请发布您的答案,谢谢。

4

1 回答 1

0

要应用用户角色替换的更改,该用户应重新登录。基本上假设我们有一些服务叫做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
}
于 2019-01-12T14:27:46.650 回答