I am using JWT bearer authentication, configured as follows.
My problem is that the middleware is executing before the token is validated.
It looks like you've found a good solution to your problem but I thought I'd add an answer to explain the behavior you're seeing.
Since you have multiple authentication schemes registered and none is the default, authentication does not happen automatically as the request goes through the pipeline. That's why the HttpContext.User
was empty/unauthenticated when it went through your custom middleware. In this "passive" mode, the authentication scheme won't be invoked until it is requested. In your example, this happens when the request passes through your AuthorizeFilter
. This triggers the JWT authentication handler, which validates the token, authenticates and sets the Identity, etc. That's why (as in your other question) the User
is populated correctly by the time it gets to your controller action.
It probably doesn't make sense for your scenario (since you're using both cookies and jwt)... however, if you did want the Jwt authentication to happen automatically, setting HttpContext.User
for other middleware in the pipeline, you just need to register it as the default scheme when configuring authentication:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)