1

I'm using the WindowsAzureActiveDirectoryBearerAuthenticationOptions middleware in a web api project and the important parts of my Startup.cs look like this:

public static void ConfigureApp(IAppBuilder appBuilder)
{    
   HttpConfiguration config = new HttpConfiguration();

   config.MapHttpAttributeRoutes();

   appBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(
        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
               Tenant = "xx-xx-xx",
               TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidAudience = "yy-yy-yy",
                    ValidateAudience = true
                }
         });

   config.Filters.Add(new AadAuthorizeAttribute());
   appBuilder.UseWebApi(config);
}

The problem is that if I try to access http://localhost/api/404route (which does not exist) I get a 404 when I should have gotten a 401 (since the request from browser does not have any bearer token, etc. and is unauthenticated). If I go to a route that exists, I get 401 as expected. I believe this is because the AadAuthorizeAttribute triggers the middleware execution, which does not happen when webapi cannot find the controller/action.

How do I trigger the authentication for any request even if the route does not exist while using this simple middleware (preferably don't want to write my own)?

AzureMinotaur
  • 646
  • 2
  • 9
  • 22

1 Answers1

1

Authentication middleware is always run. But it won't throw 401s, that's just not its job. It only checks for identity and adds it to the request if any are found.

What you need is something like this:

app.Use(async (ctx, next) =>
{
    if (ctx.Authentication.User.Identity.IsAuthenticated == false)
    {
        ctx.Response.StatusCode = 401;
        return;
    }
    await next();
});

Put this after your authentication middleware, and it'll send back a 401 for any unauthenticated requests, going to a valid path or not.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • I see, but then is the answer mentioned in this stackoverflow incorrect? http://stackoverflow.com/questions/32474133/how-does-usewindowsazureactivedirectorybearerauthentication-work-in-validating-t It mentions "The [Authorize] decoration in the controller or whichever method we specify triggers the Owin security handler to validate the token and generates the claims." – AzureMinotaur Apr 11 '17 at 21:13
  • Yes, that answer is incorrect. OWIN middleware run on every request and also have the power to halt execution and return a response immediately like here. The only thing is that this behaviour only occurs when the authentication middleware runs in Active mode `AuthenticationMode = AuthenticationMode.Active`. That is the default setting if you don't change it. That means it attempts to find identity info in every request, and create a ClaimsPrincipal if it finds valid info. – juunas Apr 12 '17 at 07:58