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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With