Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why UseAuthentication must be before UseMvc in NET Core 2.0

In NET Core 2.0 when I have:

app.UseAuthentication();
app.UseMvc();

My app handles correctly JWT authorization header, but when above lines are in a different order

app.UseMvc();
app.UseAuthentication();

magic can happen. Like for the first request, everything is fine but second, received 401 response (this behaviour is the most interesting).

So the question is why the order of this two middlewares has such strange impact? I understand the correct order, but I don't understand the strange behaviour in first request

like image 565
Piotr Stapp Avatar asked Mar 14 '18 11:03

Piotr Stapp


1 Answers

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.

like image 79
Alexey Andrushkevich Avatar answered Sep 28 '22 17:09

Alexey Andrushkevich