为什么UseAuthentication必须在NET Core 2.0中的UseMvc之前 [英] Why UseAuthentication must be before UseMvc in NET Core 2.0

查看:598
本文介绍了为什么UseAuthentication必须在NET Core 2.0中的UseMvc之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆