【问题标题】:ASP.NET Core JWT Authentication to secure webAPI [Authorize] attribute Error 401 UnauthorizedASP.NET Core JWT 身份验证以保护 webAPI [Authorize] 属性错误 401 Unauthorized
【发布时间】:2021-05-20 13:21:31
【问题描述】:

我开发 API POST 并且它工作正常,但是当我添加 [Authorize] 属性时,即使我在标题中添加正确的令牌,邮递员也会收到 401 Unauthorized

 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
           
            [HttpPost]
            
            public async Task<ActionResult> Post([FromBody] CViewModel cVM)
            {
    // to do
            }

我只想使用 JWT TOKEN 保护我的 API, API 身份验证正常工作并生成令牌,但我不知道为什么添加 [Authorize] 属性我得到错误 401 Unauthorized 在我的 POST API 中。

谢谢!

【问题讨论】:

标签: asp.net-core asp.net-web-api jwt token authorize-attribute


【解决方案1】:

添加[Authorize]时,只有携带token才能成功访问该动作。一种可能性是 url 与这条路线无关。但更重要的原因是您没有正确配置登录路径,或者登录路径不存在。所以你可以在启动时检查配置。

【讨论】:

  • 谢谢你的回复,我有在 postMan 中工作的 API,没有 [Authorize] 所以 URL 是正确的,我用 POSTMAN 测试它我只想在数据库中添加对象,当我写 [Authorize] (AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] 我得到 401 Unauthorized 即使我在标头中添加了令牌:/
  • 我编辑了我的问题并添加了我的启动
  • 使用Jwt认证方案时如何发送token?
  • 我有用于身份验证的 api 帖子,接受电子邮件和密码并返回我现在添加的令牌问题中的代码
【解决方案2】:

问题是我在启动和生成令牌方法中使用了不同的密钥

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 2021-10-14
    • 2021-10-27
    • 2018-12-03
    • 2017-09-20
    • 2016-11-02
    • 2019-04-19
    • 2019-09-06
    • 2021-04-20
    相关资源
    最近更新 更多