Ajax request to unauthorized action returns login page inside the div MVC 4

2.2k views Asked by At

I am building ASP.Net MVC 4 application and i have putted [Authorize] attribute at the top of my controller.

When the session is over and i try to trigger an ajax request to a method from that controller the redirect to login page, result from the unauthorized access attempt, is done inside the div. Here is an example ajax i do:

var url = '/Admin/GetData/';
                    $.ajax({
                        url: url,
                        data: { param1: param1, param2: param2 },
                        type: 'POST',
                        datatype: 'json',
                        success: function (data) {
                            $('#myDiv').html(data);
                        },
                        error: function () { alert('Error with loading the data.'); }
                    });

This ajax takes some parameters and executes this method:

        public ActionResult GetData(int param1, string param2)
    {
        if (param1> 0 && param2!= null)
        {
            List<Objects> myData = myRepo.Method(param1, param2);
            return PartialView("_DataTablePartial", myData);
        }

        else
        {
            List<Objects> myData = new List<Objects>();
            return PartialView("_DataTablePartial", myData);
        }
    }

Here is a screenshot of the result. enter image description here

How can i handle the unauthorized error to redirect the whole page to the login page and not to replace the content of the div with the login page ?

1

There are 1 answers

1
Moeri On

I use the following technique in my applications:

Javascript:

/**
    Ajax error registrar, so that ajax requests that are blocked because of an authorization problem result in a redirection to the login page
*/
$(document).ajaxError(function (event, jqXhr, ajaxSettings, thrownError) {
    switch (jqXhr.status) {
        case 401:
            var response = $.parseJSON(jqXhr.responseText);
            window.location = response.returnUrl;
            break;
        default:
            break;
    }
});

C#:

public class UnauthorizedJsonResult: JsonResult
{
    public UnauthorizedJsonResult(string returnUrl)
    {
        Data = new { returnUrl };
        JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        base.ExecuteResult(context);
        context.HttpContext.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
        context.HttpContext.Response.End();
    }
}

public class SomeController : Controller
{
    public ActionResult SomeAjaxCall()
    {
        if( /* some logic */ )            
            return new UnauthorizedJsonResult("/login");
    }
}

Or with an authorize attribute:

public class YourCustomAuthorizeAttribute: FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.Result = new UnauthorizedJsonResult("/login");
    }
}

[YourCustomAuthorize]
public class SomeController : Controller
{
    public ActionResult SomeAjaxCall()
    {
        // logic
    }
}