【发布时间】:2015-12-09 18:09:30
【问题描述】:
我想实现一个白名单方法,默认情况下将应用 [Authorize(Roles = "Admin")] 属性。然后我想在白名单操作中指定[AllowAnonymous] 或[AllowMember]。
所以我需要创建一个类似于AllowAnonymous 的属性,但只授予“成员”角色的访问权限。 (和AllowAnonymous 一样,它应该覆盖任何可能在控制器上作为全局过滤器生效的Authorize 属性。)
我最初尝试从AllowAnonymousAttribute 继承,但我发现它是密封的。我用谷歌搜索了“继承允许匿名”,但答案让我无法理解。
我的方法是否明智?如何创建这样的属性?
更新
按照 NightOwl888 的建议和来自this page 的一些代码,我有:
创建了两个
Attributes,一个允许会员,另一个公开继承了 AuthorizeAttribute 以创建一个新的,我将 应用为全局过滤器
在 AuthorizeCore() 方法中插入了几个方法来检查属性并返回 true
我希望我没有在下面的代码中做任何愚蠢的事情......如果它看起来不错(或不是),我会很感激抬头(或向下)。
谢谢。
namespace FP.Codebase.Attributes
{
public class AllowPublicAccessAttribute : Attribute
{}
public class AllowMemberAccessAttribute : Attribute
{}
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.HttpContext.Items["ActionDescriptor"] = filterContext.ActionDescriptor;
base.OnAuthorization(filterContext);
}
private bool IsAllowPublicAccessAttributeAppliedToAction(ActionDescriptor actionDescriptor)
{
return (actionDescriptor.IsDefined(typeof(AllowPublicAccessAttribute), inherit: true)
|| actionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowPublicAccessAttribute), inherit: true));
}
private bool IsAllowMemberAccessAttributeAppliedToAction(ActionDescriptor actionDescriptor)
{
return (actionDescriptor.IsDefined(typeof(AllowMemberAccessAttribute), inherit: true)
|| actionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowMemberAccessAttribute), inherit: true));
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var actionDescriptor = httpContext.Items["ActionDescriptor"] as ActionDescriptor;
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (IsAllowPublicAccessAttributeAppliedToAction(actionDescriptor))
{
return true;
}
if (IsAllowMemberAccessAttributeAppliedToAction(actionDescriptor) && user.IsInRole("Member"))
{
return true;
}
if (!user.Identity.IsAuthenticated)
{
return false;
}
var _usersSplit = SplitString(Users);
var _rolesSplit = SplitString(Roles);
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
{
return false;
}
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
{
return false;
}
return true;
}
// copied from https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/AuthorizeAttribute.cs
internal static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
{
return new string[0];
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}
}
【问题讨论】:
标签: asp.net-mvc authorization custom-attributes authorize-attribute