I have created a custom authorization attribute which I have applied to a number of controllers. I now find that I need to handle Ajax requests and gracefully redirect.
Ronnie's answer here looks like exactly what I require, however instead of the JSON object I can only ever get a generic 403 forbidden html page as a result.
SsoAuthorizeAttribute:
public class SsoAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
if (filterContext.HttpContext.Request.IsAjaxRequest()) {
var urlHelper = new UrlHelper(filterContext.RequestContext);
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult {
Data = new {
Error = "NotAuthorized",
SingleSignOn = Site.SSOUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
} else {
filterContext.Result = new RedirectResult(Site.SSOUrl, false);
}
}
public override void OnAuthorization(AuthorizationContext filterContext) {
if (true) {
HandleUnauthorizedRequest(filterContext);
}
}
}
}
Javascript:
$(function () {
$(document).ajaxError(function (e, xhr) {
if (xhr.status == 403) {
//xhr.responseText always contains a generic 403 page instead of the JSON object
var response = $.parseJSON(xhr.responseText);
window.location = response.LogOnUrl;
}
});
});
If I change the status code to 200:
filterContext.HttpContext.Response.StatusCode = 200;
It works as I would expect.
How do I override the behavior I am experiencing so that I can return the JSON object with a 403 status?