Running custom C# middeware after authentication

Viewed 51

In my Program.cs I have

            app.UseRouting();
            app.UseCors();
            app.UseAuthentication();
            app.UseMiddleware<MyCustomMiddleware>();
            app.UseAuthorization();
            app.UseEndpoints(cfg =>
            {
                cfg.MapControllers();
                cfg.MapFallbackToController("Get", "Branding");
            });

with the expectation that my custom middleware would run after authentication and therefore I would have a claims identity to play with.

But when my MyCustomMiddleware.Invoke is called the _next is AuthorizationMiddleware as expeted, but the context.User is not authenticated and has no claims.

However, the context.User is authenticated and has claims after _next.Invoke(context) returns.

So it looks like the middleware is running out of order.

What could be wrong?!

1 Answers

I believe that the behaviour you are seeing is correct if the AuthenticationMiddleware has yet to complete authenticating the user. Depending on your selected authentication scheme, the AuthenticationMiddleware may have returned back a HTTP 401 Challenge response to the client, or a HTTP 301 redirect to send the user to the authentication provider's login page if using OAuth. Check the context.Response inside of your middleware to be sure that this is in fact what is happening.

If the AuthenticationMiddleware hasn't short circuited the middleware, the unauthenticated request will still be passed on to the subsequently registered middleware before the response is sent back to the client.

Typically, its recommended that the AuthorizationMiddleware is ordered immediately after the AuthenticationMiddleware (see: ASP.NET Core Fundamentals Built-in Middleware), so that the user is properly authenticated and claims have been added. Because you have chosen to put a middleware in between, you are seeing the in-between process that ASP.NET core is following to authenticate and provide claims for the user.

Related