Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom authorization filter always returning 404 when I'm trying to force a 401

I am trying to write my own authorization attribute where I run through some custom checks on any web api method with the CustomAuthorization attribute.

My code is as follows:

   [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class CustomAuthorization : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(AuthorizationContext context)
        {
            //// Attempt 1 - 404 error.  
            //// Doesnt block method with this attribute from executing (not desired behaviour).

            //context.HttpContext.Response.StatusCode = 401;
            //return; 

            //// Attempt 2 - 404 result. 
            //// Code with attribute doesnt execute (desired).
            //// Error thrown says:  An exception of type 'System.Web.Http.HttpResponseException' occurred in <namespace> but was not handled in user code
            //// Additional information: Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.

            //throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));

            // Attempt 3 - 404 result. 
            // Code with attribute doesnt execute (desired).
            context.Result = new HttpUnauthorizedResult();
        }
    }

The problem I'm having is that I'm getting a 404 response from the web api instead of an expected 401. What am I doing wrong?

This is asp.net core 1.

Thanks in advance!

like image 210
Rob McCabe Avatar asked Apr 27 '16 16:04

Rob McCabe


1 Answers

It may be because you have authentication setup to redirect to a login page for 401 responses and that login page is not being found (happened to me).

like image 187
Clint B Avatar answered Sep 27 '22 18:09

Clint B