为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
心有法竹 2022-12-24 10:06:39
我正在研究 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 中尝试过认证方案但没有什么不同。
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

好的,我在这篇博文.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();

        });

    }

所以这解决了我的问题。


查看完整回答
反对 回复 2022-12-24
  • 1 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号