ASP.NET Core中的授权.对于[Authorize]属性始终为401未经授权 [英] Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute

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

问题描述

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

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中的授权.对于[Authorize]属性始终为401未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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