How do you deal with authorisation on actions that return results other than ViewResult? How do you deal with authorisation on actions that return results other than ViewResult? json json

How do you deal with authorisation on actions that return results other than ViewResult?


Use Request.IsAjaxRequest(), e.g.:

public sealed class AjaxAuthorizeAttribute : AuthorizeAttribute{    public AjaxAuthorizeAttribute() : base()    {    }    public override void OnAuthorization(AuthorizationContext filterContext)    {        // Extends the original Web.MVC.AuthorizeAttribute for Ajax calls.        // Basically if the request is not authorized and the request is an AJAX Request.        // then we simply set the stats Code to 403 and set an empty Result, in order to         // determine in Javascript if the AJAX call came back completed and valid.        base.OnAuthorization(filterContext);        if (filterContext.Result == null)        {            return;        }        else if (filterContext.Result.GetType() == typeof(HttpUnauthorizedResult)                  && filterContext.HttpContext.Request.IsAjaxRequest())        {            filterContext.Result = new ContentResult();            filterContext.HttpContext.Response.StatusCode = 403;        }    }}

Note 403, not 401, since ASP.NET intercepts 401s and turns them into HTML error pages. It doesn't matter what the AJAX call expected to receive; it can still see the status code.


I think you'll need to pass in that information with the redirection.

A couple ways you could handle this:

  • Consider making separate action methods for each type of response you need - UnauthorizedJson, UnauthorizedHtml, UnauthorizedEtc... that corresponded to the original action response type

  • Pass in the format information with the redirection by adding another parameter to the Unauthorized method and appending it to the URL in your filter