I have two attributes :
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;
}
}
I define ActionAuthorizeAttribute
as a global attribute.
So I need this 3 items:
1- If did not log in(!User.Identity.IsAuthenticated
): Go to LogIn Page Accounts/LogIn
.
I must mention the LogIn
action marked with AnonymousAllowedAttribute
.
2- If log in (User.Identity.IsAuthenticated
) and action or controller have AnonymousAllowedAttribute
then authorize is true (don't need any authorization).
3- If log in (User.Identity.IsAuthenticated
) and action haven't AnonymousAllowedAttribute
return CustomeCheck()
method
I try second one by override OnAuthorization()
method as you see.
and third one by followings:
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext){
if(!httpContext.User.Identity.IsAuthenticated)
return false;
return CustomeCheck();
}
but when I did not log in always return:
IIS 7.5 Error Details:
HTTP Error 401.0 - Unauthorized
with this URL: http://myProject/Accounts/LogIn?ReturnUrl=%2f
where is the problem? how can implement ActionAuthorizeAttribute
to achieve this 3 goals?
Update
I find answer : the problem is the : AnonymousAllowedAttribute
need to inherit from Attribute
rather than AuthorizeAttribute
.
the problem is: The AnonymousAllowedAttribute
need to inherit from Attribute
rather than AuthorizeAttribute
.
when AnonymousAllowedAttribute
inherit from AuthorizeAttribute
so need to authorize but I create that to reduce Authorization!!