我有以下带有自定义授权属性的控制器:
[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")]
我正在将其作为字符串传递,我需要在我的CustomAuthorize方法中将其转换为数组吗?
IsInRole
返回true,检查!_allowedRoles.Any(user.IsInRole)
。 - Nkosiparams string[] roles
作为参数传递,还是授权属性已经有了Roles
? - adam78[CustomAuthorize("Editor", "Admin")]
。 - Nkosi