Authorization attribute validation Issue: 404 status code is returned instead of 401 status code
In my application, I was using an API service to be used by external applications, where I needed to implement the authorization of valid requests by validating the supplied token in the Header part of user request. For that, API service in MVC controller was annotated with custom authorization attribute as shown below –
[System.Web.Mvc.HttpPost] [CustomAuthorization] public string MyWebMvcService([FromBody]requestBody) { // your code here…. }
The purpose of the “Custom Authorization” attribute was to return the ‘unauthorized response’ on the failure of token verification. But I was facing the issue of status response. Even though I was returning Unauthorized Response, I was still receiving 404 in response.
This issue appeared because there were form authentication settings in web configuration settings. If form authentication settings are applied in your application, then authorization attribute redirects the user to redirect URL specified in case of authorization failure i.e for 401 Unauthorized status.
Although I did not specify the redirect URL in the settings, only timeout settings, still I was getting that issue. But providing forms of authentication settings were affecting the API response. For that .net 4.5 and above versions provides a fix to remove the effect of form authentication settings for 401 status in special scenarios.
Below is the code snippet showing the sample Custom Authorization attribute along with the fix.
public class CustomAuthorization: System.Web.Mvc.AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { string authValue = filterContext.HttpContext.Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authValue) || !IsTokenValid(authValue)) { // return HTTP 401 Unauthorized to client if authorization fails // this works normally if form authentication settings are not applied in config file filterContext.Result = new HttpUnauthorizedResult(); // below statement is used to fix status code in response filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; } } }