Asp.net mvc 具有排除属性的全局自定义授权属性
我有两个特点:Asp.net mvc 具有排除属性的全局自定义授权属性,asp.net-mvc,asp.net-mvc-3,authorization,action-filter,authorize-attribute,Asp.net Mvc,Asp.net Mvc 3,Authorization,Action Filter,Authorize Attribute,我有两个特点: public class AnonymousAllowedAttribute : AuthorizeAttribute { } public class ActionAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { bool skipAuthorization =
public class AnonymousAllowedAttribute : AuthorizeAttribute { }
public class ActionAuthorizeAttribute : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext) {
bool skipAuthorization =
filterContext.ActionDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true)
||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true);
if(!skipAuthorization)
base.OnAuthorization(filterContext);
}
bool CustomeCheck() {
bool result = //My Checks
return result;
}
}
我将actionAuthorizationAttribute
定义为全局属性
所以我需要这3项:
1-如果未登录(!User.Identity.IsAuthenticated
):转到登录页面帐户/LogIn
。
我必须提到用匿名允许属性标记的登录
操作
2-如果登录(User.Identity.IsAuthenticated
)且操作或控制器具有AnonymousAllowedAttribute
,则授权为真(不需要任何授权)
3-如果登录(User.Identity.IsAuthenticated
)并且操作没有AnonymousAllowedAttribute
返回CustomeCheck()
方法
如您所见,我通过重写OnAuthorization()
方法尝试了第二种方法
第三种方法是:
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext){
if(!httpContext.User.Identity.IsAuthenticated)
return false;
return CustomeCheck();
}
但当我没有登录时,总是返回:
IIS 7.5错误详细信息:
HTTP错误401.0-未经授权
使用此URL:http://myProject/Accounts/LogIn?ReturnUrl=%2f
问题在哪里?如何实现这三个目标
更新
我找到了答案:问题是:AnonymousAllowedAttribute
需要从属性继承,而不是AuthorizeAttribute
问题是:AnonymousAllowedAttribute
需要从属性继承,而不是AuthorizeAttribute
当AnonymousAllowedAttribute
继承自AuthorizeAttribute
时,需要授权,但我创建它以减少授权 问题是:匿名AllowedAttribute
需要从属性
继承,而不是授权属性
当AnonymousAllowedAttribute
继承自AuthorizeAttribute
时,需要授权,但我创建它以减少授权