【问题标题】:ASP.NET MVC Identity:how do I Extend AspNetUserRoles tableASP.NET MVC 身份:如何扩展 AspNetUserRoles 表
【发布时间】:2015-07-10 17:56:00
【问题描述】:

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

所以如果一个用户登录不同的部门,他将扮演不同的角色。 有谁知道该怎么做?提前致谢!

【问题讨论】:

  • 如果您在 AspNetUserRoles 表中添加一列,则需要对基础架构进行大量更改,包括过滤器。最简单的方法是使用 Department - Role Name 添加角色。例如,人力资源部门 - 经理.
  • 或使用 UserId RoleId DepartmentId 创建自己的表
  • 不确定如何首先使用 EF 代码对 3 键表进行建模。任何帮助将不胜感激。
  • 你有没有找到解决办法?

标签: asp.net-mvc asp.net-identity


【解决方案1】:

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

示例属性用法

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 2015-02-09
    • 2019-05-29
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多