Wednesday, July 15, 2015

Skip Authorization for AllowAnonymous Attribute in Custom Authorization filter

If you use custom Authorization, attribute in controller level and want to allow any action for anonymous user then maybe you have face this issue already or searching for solution.

Yes, If you implement your own authorization mechanism by inheriting AuthorizeAttribute class and at same time allow any action by decorating “AllowAnonymous “ , it will not work.

To make it work, we have to add little spice in custom authorization filter class. Here is my example where I am bypassing authorization challenge if the action or controller has “AllowAnonymous” attribute.

public override void OnAuthorization(AuthorizationContext filterContext)
        {

            bool skipAuthorization = filterContext.
                                                    ActionDescriptor.
                                                    IsDefined(typeof(AllowAnonymousAttribute), true)
                                                    ||                      filterContext.ActionDescriptor.
                                                     ControllerDescriptor.
                                                    IsDefined(typeof(AllowAnonymousAttribute), true);

            if (skipAuthorization)
            {
                return;
            }


            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.HttpContext.Response.StatusCode = 401;
                    filterContext.Result = new HttpStatusCodeResult(401, "Please login to continue");
                    filterContext.HttpContext.Response.End();

                    //FormsAuthentication.SignOut();
                }
            }
        }


The solution is very simple. Just w are checking the action or controller containing AllowAnonymous attribute or not? If so, then we are returning flow from there by skipping authorization challenge. 

No comments:

Post a Comment