gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 标识 :how do I Extend AspNetUserRoles table

转载 作者:行者123 更新时间:2023-12-01 19:00:13 27 4
gpt4 key购买 nike

在ASP.NET MVC Identity中,用户和角色的关系数据保存在AspNetUserRoles表中,该表有两个字段:UserId,RoleId,但我想向该表添加其他字段,例如部门字段。

所以如果一个用户登录到不同的部门,他就会有不同的角色。有人知道该怎么做吗?提前致谢!

最佳答案

我建议您调查 ASPNet 用户声明。您可以使用身份管理器为用户分配不同的声明,并根据用户的声明类型允许或不允许他访问。创建一个自定义声明属性,该属性将放置在各个 Controller 的顶部以对用户进行身份验证。这必须根据您的需求来实现。然后,自定义属性将在 Controller 执行之前触发,如果允许使用,他将通过。否则返回您选择的错误页面。

属性使用示例

[ClaimsAuthorize(ClaimsData.EditAddress)]
public ActionResult CitiesPartial()

属性认证

 public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
private readonly string _claimType;
public ClaimsAuthorizeAttribute(string type)
{
_claimType = type;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
var user = (ClaimsPrincipal)HttpContext.Current.User;

if (user.HasClaim(_claimType, "True"))
{
base.OnAuthorization(filterContext);
}
else
{
HandleUnauthorizedRequest(filterContext, _claimType + " Not Allowed ");
}
}

protected void HandleUnauthorizedRequest(AuthorizationContext filterContext, string message)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "ClaimNotAuthorized" },
{ "controller", "Home" },
{"errorMessage", message }
});
}

public static bool AuthorizedFor(string claimType)
{
var user = (ClaimsPrincipal)HttpContext.Current.User;
return user.HasClaim(claimType, "True");
}
}

希望这有帮助。

关于asp.net-mvc - ASP.NET MVC 标识 :how do I Extend AspNetUserRoles table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347291/

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