ASP.NET Core 中的授权.总是 401 Unauthorized [Authorize] 属性 [英] Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute

查看:48
本文介绍了ASP.NET Core 中的授权.总是 401 Unauthorized [Authorize] 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在 ASP.NET Core 中创建授权.我使用了这里的教程 TUTORIAL

For the first time I'm creating Authorization in ASP.NET Core. I used tutorial from here TUTORIAL

问题是当我从邮递员发送请求时:

The problem is when I sending request from postman:

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6I...

到我的用 [Authorize] 属性装饰的控制器中的方法.

to my method in controller decorated with [Authorize] attribute.

我总是收到 401 Unauthorized ......我看到了那个教程下面的评论,似乎有些人也有类似的问题.我不知道如何解决这个问题.

I receive 401 Unauthorized always... I saw comments bellow that tutorial and it seems that some people have similar issue also. I've no idea how I can solve this problem.

推荐答案

应他人要求,这里是答案:

At the request of others here is the answer:

问题出在 Startup.cs 中的中间件顺序

The problem was with the middleware order in Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ConfigureAuth(app); // your authorisation configuration

    app.UseMvc();
}

为什么中间件顺序很重要?如果我们将 app.UseMvc() 放在首位 - 那么 MVC 操作将进入路由,如果他们看到 Authorize 属性,他们将控制其处理,这就是我们收到 401 Unauthorized 错误的原因.

Why middleware order is important? If we put app.UseMvc() first - then the MVC actions would get in the routing and if they see the Authorize attribute they will take control of its handling and that's why we receives 401 Unauthorized error.

我希望它可以帮助某人;)

I hope it helps someone ;)

这篇关于ASP.NET Core 中的授权.总是 401 Unauthorized [Authorize] 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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