Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Mvc custom mechanism to handle unauthorized request

Tags:

For my website i want following behaviors for secured controller(or action)

if a user makes a normal request redirect to login page (which i have easily able to do)

if request is Ajax type Request.IsAjaxRequest()==true, return status code 401

How can i create a filter for this??

like image 450
Rusi Nova Avatar asked Aug 09 '11 05:08

Rusi Nova


2 Answers

 public class MyCustomAuthorize : AuthorizeAttribute
{
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //if ajax request set status code and end Response
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.HttpContext.Response.End();
            }

            base.HandleUnauthorizedRequest(filterContext);
        }
}

Create a filter like above, it will return status code 401 for unauthorized request if request is made thru ajax.

If you are using jQuery you can do as below

jQuery.ajax({
statusCode: {
    401: function() {
      alert('unauthrized');
    },

  /*other options*/
});
like image 117
Praveen Prasad Avatar answered Sep 22 '22 17:09

Praveen Prasad


In addition to the accepted answer, I needed to put this line of code in to prevent FormsAuthentication from redirecting to the login page..

filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

I then removed filterContext.HttpContext.Response.End();

var unauthorizedResult = new JsonResult
{
    Data = new ErrorResult() {Success = 0, Error = "Forbidden"},
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
    // status code
    filterContext.HttpContext.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
    // return data
    filterContext.Result = unauthorizedResult;
    filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
}
like image 41
TWilly Avatar answered Sep 18 '22 17:09

TWilly