简体   繁体   English

如何为登录用户添加和启用OWIN角色?

[英]How to add and enable OWIN role to a logged in user?

I'm using MVC 5 with OWIN authentication. 我正在使用带有OWIN身份验证的MVC 5。 When adding a role to a signed in user it won't take effect until user relogs: 向已登录用户添加角色时,只有在用户重新登录后才会生效:

    [Authorize(Roles = "Role1")]
    public async Task<ActionResult> Action()
    {
        var currentUser = AuthenticationManager.User;
        var currentUserId = currentUser.Identity.GetUserId();
        var result = await UserManager.AddToRoleAsync(currentUserId, "Role2"); //result confirms role added 

        return RedirectToAction("AnotherAction", "Controller");
    }

    // not accessible until relog
    [Authorize(Roles = "Role2")]
    public ActionResult AnotherAction()
    {
        return View();
    }

How do make role changes take effect immediately? 如何使角色更改立即生效?

I believe that the AddUserToRole method does the assignment at the database level. 我相信AddUserToRole方法在数据库级别执行赋值。 While this probably needs to happen also, what you need to do is refresh the current identity. 虽然这可能也需要发生,但您需要做的是刷新当前身份。

Short answer: Cast the IPrincipal to a ClaimsPrincipal and cast the IIdentity to a ClaimsIdentity. 简短回答:将IPrincipal投射到ClaimsPrincipal并将IIdentity转换为ClaimsIdentity。 Then you can just add the claim. 然后你可以添加声明。

 ClaimsPrincipal currentPrincipal = (ClaimsPrincipal)this.User;
 ClaimsIdentity currentIdentity = (ClaimsIdentity)currentPrincipal.Identity;

 currentIdentity.AddClaim(new Claim(ClaimTypes.Role, "Role2"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM