ASP.NET MVC How to Handle Unauthorized Response in JSON for Your API

Assuming you want to prepare some JSON API in your ASP.NET MVC with authorization.

To share the same authorization logics for our Controller Action, what we should probably do is to implement our own FilterAttributes.

It can be as simple as:

ApiAuthorizeAttribute.cs
public class ApiAuthorizeAttribute : ActionFilterAttribute, IAuthorizationFilter
{
//Property Inject here!
public IAuthTokenService AuthTokenService { get; set; }
public ApiAuthorizeAttribute()
{
}
#region IAuthorizationFilter member
public void OnActionExecuting(ActionExecutingContext filterContext)
{
bool authTokenValid = IsRequestTokenValid(filterContext);
if (!authTokenValid)
{
filterContext.Result = new JsonResult
{
Data = new { Success = false, Data = "Unauthorized" },
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}

Note we are using property injection here for the IAuthTokenService here, check out Inject Properties Into FilterAttributes for more information.

HTTP status codes

In order to add our HTTP status codes, we can simple add the following line:

ApiAuthorizeAttribute.cs
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new JsonResult
{
Data = new { Success = false, Data = "Unauthorized" },
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Problem: The default ASP.NET forms authentication redirect behaviour

The default ASP.NET forms authentication behaviour will convert HTTP 401 status codes to 302 in order to redirect to the login page. This probably not we want here as we are expecting a JSON for our API result.

Solution

If you are using .Net 4.5, you can apply the new HttpResponse.SuppressFormsAuthenticationRedirect property.

If you are using .Net 4.0 or lower version, it seems it cannot be done at the moment, but we may try to use different HTTP status code like 403