Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally use Middleware Only On Endpoints That Have Authorize Attributes

I have writted a piece of middleware that I only want to run on Authenticated endpoints.

So Basically I want it in my implementation to only trigger when a controller or action is marked with [Authorize]. Any controller action that does not require authhorization should not require my middleware to trigger.

I've found the UseWhen functionality but the best i've managed is that the middleware only triggers once a user is authenticated. However if will still trigger on all endpoints after the user has signed in.

Here is my current conditional.

        app.UseWhen(context => context.User.Identity.IsAuthenticated, appBuilder =>
        {
            appBuilder.UseAutomaticallyRefreshTokenMiddleware();
        });

I think i just need to change that context check, but not exactly sure what to replace it with.

like image 510
Lee Avatar asked Jun 28 '19 17:06

Lee


1 Answers

The middlewares get registered to the pipeline based on the condition and the registrations are done only at startup. The registrations are not modified afterwards. Once they are a part of the pipeline, they are a part of the pipeline. One thing you can do is to customize the Authorize attribute. Inherit the Authorize attribute, and then inside that run the logic you are running inside your middleware.

like image 160
Shahzad Avatar answered Nov 01 '22 22:11

Shahzad