【问题标题】:Auth0 api returning 401 www-authenticate: Bearer error="invalid_token" in .net core web apiAuth0 api 返回 401 www-authenticate: Bearer error="invalid_token" in .net core web api
【发布时间】:2019-12-12 02:12:43
【问题描述】:

我使用 auth0 和 .net core web api,下面是我的配置。

  1. 在我的 ConfigureServices() 中有

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.Authority = "https://xxxxxxx.auth0.com/";
        options.Audience = "https://localhost:5001";
    });
    
  2. 在我的 Configure() 方法中,我有

    // 2. Enable authentication middleware
    app.UseAuthentication();
    app.UseMvc();
    

最后在我的 HomeController.cs 中

    [HttpGet("private")]
    [Authorize]
    public IActionResult Private()
    {
        return Ok(new
        {
            Message = "Hello from a private endpoint! You need to be authenticated to see this."
        });
    }

当我尝试使用正确的访问令牌、使用邮递员或我的反应应用程序访问端点时,我得到 401 未授权或www-authenticate: Bearer error="invalid_token"

我按照文档中的示例进行操作,无法弄清楚我在这里做错了什么。请指教。

【问题讨论】:

  • 如何获取访问令牌?

标签: asp.net-core asp.net-core-webapi auth0


【解决方案1】:

通过配置令牌验证尝试这种方式

.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = "https://xxxxxxx.auth0.com/",
        ValidateAudience = true,
        ValidAudience = "https://localhost:5001",
        ValidateLifetime = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(YourSecretKey)),
        ValidateIssuerSigningKey = true
    };
});

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      尝试明确指定您使用的方案:

      [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
      

      而不是

      [Authorize]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-21
        • 2021-07-26
        • 2022-07-12
        • 2021-02-06
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多