Asp.Net MVC 5 - 自定义授权不起作用?



我有以下具有自定义授权属性的控制器:

[CustomAuthorize(Roles = "Editor, Admin")]
public ActionResult Test()
{
//...
}

这是我的自定义授权代码:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private readonly string[] _allowedRoles;
public CustomAuthorizeAttribute(params string[] roles)
{
_allowedRoles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");

var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
if (_allowedRoles.Length > 0 && !_allowedRoles.Any(user.IsInRole))
{
return false;
}

return true;
}

}

自定义授权甚至对于不是编辑者或管理员的用户也返回true

我认为问题是这样的:

[CustomAuthorize(Roles = "Editor, Admin")]

我将其作为字符串传递,我需要在我的自定义授权方法中将其转换为数组???

属性的当前定义不引用Roles属性,也不会填充_allowedRoles字段。

这就是为什么您的属性始终返回true的原因。

查看自定义属性的重构逻辑

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute {
private readonly string[] _allowedRoles;
public CustomAuthorizeAttribute(params string[] roles) {
_allowedRoles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null)
throw new ArgumentNullException("httpContext");
var user = httpContext.User;
if (user?.Identity?.IsAuthenticated) {
if (isInRole(user, _allowedRoles)) {
return true;
}
if (!string.IsNullOrWhiteSpace(Roles)) {
var roles = Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (isInRole(user, roles))
return true;
}
return true;
}
return false;
}
bool isInRole(IPrincipal user, string[] roles) {
return roles.Length > 0 && roles.Any(user.IsInRole);
}
}

可以像这样使用

[CustomAuthorize(Roles = "Editor, Admin")]
public ActionResult Test() {
//...
}

其中将拆分角色并根据用户进行检查

或喜欢

[CustomAuthorize("Editor", "Admin")]
public ActionResult Test() {
//...
}

这将用参数数组填充属性的构造函数

首先您需要获取当前用户的角色,然后检查是否有任何角色允许用户访问控制器:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");

var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
var userRoles = ((ClaimsIdentity)User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);
if (_allowedRoles.Length > 0 && !_allowedRoles.Any(x => userRoles.Any(y => x.Equals(y)))))
{
return false;
}

return true;
}

最新更新