问题描述
在 NET Core 2.0 中,当我有:
In NET Core 2.0 when I have:
app.UseAuthentication();
app.UseMvc();
我的应用程序正确处理 JWT 授权标头,但当以上行的顺序不同时
My app handles correctly JWT authorization header, but when above lines are in a different order
app.UseMvc();
app.UseAuthentication();
魔法可能发生.就像对于第一个请求,一切都很好,但是第二个,收到了 401 响应(这种行为是最有趣的).
magic can happen. Like for the first request, everything is fine but second, received 401 response (this behaviour is the most interesting).
那么问题来了,为什么这两个中间件的顺序会有如此奇怪的影响?我理解正确的顺序,但我不理解第一个请求中的奇怪行为
So the question is why the order of this two middlewares has such strange impact? I understand the correct order, but I don't understand the strange behaviour in first request
推荐答案
因为中间件在 Configure
方法中声明的顺序实际上很重要.中间件定义了请求将通过的管道.最简单的中间件可以这样定义
Because the order of how middlewares declared in Configure
method actually matters. The middlewares define the pipeline which a request will go through. The simplest middleware can be defined like this
app.Use(async (context, next) =>
{
await next.Invoke();
});
在这个例子中,next.Invoke()
之前的代码将在请求传递到链中的下一个中间件之前执行.当所有后续中间件都执行完毕后,它之后的所有内容都会被执行.现在,对于您的问题,身份验证中间件是在 MVC 之前定义的,因为通过这种方式,身份验证中间件可以停止请求并在无法通过身份验证时返回 HTTP 状态 403 或将请求重定向到登录页面的 HTTP 状态 302.
In this example the code before next.Invoke()
will be executed before request is passed to next middleware in the chain. And everything what goes after it will be executed when all subsequent middlewares have been executed. Now to your question the authentication middleware is defined before MVC because in this way the authentication middleware can stop a request and return HTTP status 403 if it cannot be authenticated or HTTP status 302 to redirect request to a login page.
至于您的具体情况,第一个请求最有可能与配置的路由匹配,因此请求由 MVC 控制器处理并生成响应,而无需将其传递给下一个(身份验证)中间件.对于第二个请求(我猜它是不同的),MVC 框架没有找到与此请求匹配的路由器,因此它只是将其转发给下一个中间件,希望它知道如何处理它.
As for your specific case the first request most likely matched the configured route so request was handled by MVC controller and generated response w/o passing it to the next (authentication) middlware. For second request (I guess it's different one) the MVC framework didn't find a router matched by this request so it just forwarded it to next middleware hoping that it knows how to process it.
另一个原因是第一个请求命中不需要授权的请求,而另一个请求命中了需要授权的请求.
Another reason would be that first request hit action which doesn't require request to be authorized, when another request hit the one which requires authorization.
这篇关于为什么 UseAuthentication 必须在 NET Core 2.0 中的 UseMvc 之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!