AuthenticationMiddleware trying all schemas #26740
-
I was playing around with a custom IAuthenticationHandlerProvider which I registered using services.AddAuthentication().AddScheme(...). I have 3 schemas active. Since I had not read the documentation, I was returning true from the HandleRequestAsync (expecting 'authentication handled'), and the pipeline stopped (as per the documentation). This made me dig deeper into the Authentication middleware pipeline. What I see in AuthenticationMiddleware.cs is that all schemas are tried to authenticate against, and then again the default schemas as well. Is there a need to try and authenticate against multiple authentication methods after one of them already authenticated correctly? In my particular case, only 1 will ever hit back true. A simple check on ( context.User?.Identity?.IsAuthenticated ?? false ) could be used to skip everything and immediately call {await _next(context); return;} In fact, while I only use 3 schemas apparently, 7 get registered (with 2 distinct handlers). This means that 7 schemas get tried each time, + 1 (the default). |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
cc @HaoK |
Beta Was this translation helpful? Give feedback.
-
Right, so all schemes that implement Then only the default scheme is explicitly called to Authenticate, which is not the same thing as HandleRequest, those are usually doing things like handling redirection flows for oauth/oidc and the like. While Authenticate is doing things like reading cookies or jwt tokens. |
Beta Was this translation helpful? Give feedback.
-
Alternatively, you can think of the IAuthenticationRequestHandler stuff as a different form of routing for the auth handlers to handle specific requests. |
Beta Was this translation helpful? Give feedback.
Right, so all schemes that implement
IAuthenticationRequestHandler
are given an opportunity to handle the request.https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs#L55
Then only the default scheme is explicitly called to Authenticate, which is not the same thing as HandleRequest, those are usually doing things like handling redirection flows for oauth/oidc and the like. While Authenticate is doing things like reading cookies or jwt tokens.