So recently I had this error while I was adding authorization to a web API I have been building. If you’re here I assume you’ve had something very similar.

System.InvalidOperationException: Endpoint TestAPI.Controllers.TestController.Get (TestAPI) contains authorization metadata, but a middleware was not found that supports authorization.
Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

I was lazy and didn’t read the error properly when this first occurred. It turns out, as the error suggests, I was using app.UseAuthorization() in the wrong location. I also found other posts on StackOverflow where people had the same problem. This is a very simple mistake to make as it can be rare to come across code that needs to be executed in a specific order, depending on what you build.

So how do we fix it?

The very easy fix for this is to move app.UseAuthorization() anywhere between app.UseRouting() and app.UseEndpoints() as in this example:

app.UseRouting();
//Enable Authentication
app.UseAuthentication();
app.UseAuthorization(); //<< This needs to be between app.UseRouting(); and app.UseEndpoints();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});