Reputation: 897
I have register a global filter to authorize requests that need a cookie but I have a controller that needs to be public so I add [AllowAnonymous] attribute to the controller methods but my filter still fires and keeps redirecting. I'm not sure the best way to fix this issue.
Do I need to modify my onauthorization method to look for the [AllowAnonymous] attribute?
public class CookieAuthFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpCookie cookie = filterContext.HttpContext.Request.Cookies.Get("token");
if (cookie == null)
{
filterContext.Result = new RedirectResult("/Home/Index");
}
}
}
Upvotes: 0
Views: 38
Reputation: 56849
Do I need to modify my onauthorization method to look for the [AllowAnonymous] attribute?
You could, but it would be simpler just to move your logic so the base OnAuthorize
method (which contains the logic to scan for [AllowAnonymous]
) is unmodified.
public class CookieAuthFilter : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return httpContext.Request.Cookies.Get("token") != null;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/Home/Index");
}
}
It is better to use AuthorizeCore
to return true if the user is authorized, and use HandleUnauthorizedRequest
for the redirect.
OnAuthorization
also contains some additional logic to help it deal with output caching that you should leave in place.
Upvotes: 2