作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在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/
我是一名优秀的程序员,十分优秀!