猿问

ASP.NET Core 3 API 忽略带有 Bearertoken 的授权属性

我正在研究 ASP.NET Core Web API。我使用的是最新版本 3.0.0-preview4.19216.2。


我有问题,我的 API-Controller 忽略了 Authorize-Attribute 但在另一个控制器上 Attribute 工作正常。


    [Route("api/[controller]")]

    [ApiController]

    [Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme)]

    public class SuppliersController : ControllerBase

    {


        [HttpGet("GetAll")]

        public IActionResult GetAll()

        {

            var companyId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value); // throws nullreference exception


            return Ok();

        }

    }

但是在另一个控制器上我有类似的东西但是属性按预期工作


    [Route("api/[controller]")]

    [ApiController]

    [Authorize]

    public class UsersController : ControllerBase

    {

        [HttpGet("{id}")]

        public IActionResult GetById(int id)

        {

            var test = User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value;

        }


    }

在用户控制器中一切正常。


我也在没有的 SupplierController 中尝试过


认证方案


但没有什么不同。


心有法竹
浏览 105回答 1
1回答

UYOU

好的,我在这篇博文.NET Core 3.0 Preview 4 中的 ASP.NET Core 更新中找到了答案我必须更改我的身份验证注册顺序public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    {        app.UseHttpsRedirection();        app.UseAuthorization();        app.UseAuthentication();        app.UseRouting();        app.UseEndpoints(routes =>        {            routes.MapControllers();        });    }到 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    {        app.UseRouting();        app.UseHttpsRedirection();        app.UseAuthentication();        app.UseAuthorization();        app.UseEndpoints(routes =>        {            routes.MapControllers();        });    }所以这解决了我的问题。
随时随地看视频慕课网APP
我要回答