Accessing dotnetcore middleware AFTER a JWT Token is validated

后端 未结 2 1139
离开以前
离开以前 2021-01-18 09:42

I am using JWT bearer authentication, configured as follows.

My problem is that the middleware is executing before the token is validated.

2条回答
  •  不思量自难忘°
    2021-01-18 10:39

    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)
    

提交回复
热议问题