In NET Core 2.0 when I have:
app.UseAuthentication();
app.UseMvc();
My app handles correctly JWT authorization header, but when above lines
Because the order of how middlewares declared in Configure
method actually matters. The middlewares define the pipeline which a request will go through. The simplest middleware can be defined like this
app.Use(async (context, next) =>
{
await next.Invoke();
});
In this example the code before next.Invoke()
will be executed before request is passed to next middleware in the chain. And everything what goes after it will be executed when all subsequent middlewares have been executed. Now to your question the authentication middleware is defined before MVC because in this way the authentication middleware can stop a request and return HTTP status 403 if it cannot be authenticated or HTTP status 302 to redirect request to a login page.
As for your specific case the first request most likely matched the configured route so request was handled by MVC controller and generated response w/o passing it to the next (authentication) middlware. For second request (I guess it's different one) the MVC framework didn't find a router matched by this request so it just forwarded it to next middleware hoping that it knows how to process it.
Another reason would be that first request hit action which doesn't require request to be authorized, when another request hit the one which requires authorization.