gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:45:24 25 4
gpt4 key购买 nike

我正在使用带有 OWIN 身份验证的 MVC 5。向登录用户添加角色时,在用户重新登录之前不会生效:

    [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();
}

如何让角色变更立即生效?

最佳答案

我相信 AddUserToRole 方法在数据库级别进行分配。虽然这可能也需要发生,但您需要做的是刷新当前身份。

简短回答:将 IPrincipal 转换为 ClaimsPrincipal,并将 IIdentity 转换为 ClaimsIdentity。然后您可以添加声明。

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

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

关于c# - 如何为登录用户添加和启用 OWIN 角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com