Auth0 Home Blog Docs

Auth0 api returning 401 www-authenticate: Bearer error="invalid_token" in .net core web api

I am using auth0 with .net core web api, below are my configuration.

  1. In my ConfigureServices() I have

     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. In my Configure() method I have

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

And finally in my 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."
        });
    }

And when I try to access the endpoint, with the right access token, using postman or my react app I am getting 401 unauthorized or www-authenticate: Bearer error="invalid_token"

enter image description here

I followed the documentation for examples, cannot figure out what I am doing wrong here. Please advice.

From the screenshot it seems the issue is that the access token is not the right one. At this time, if you define a custom API in your dashboard so that Auth0 can issue access tokens for that API then the currently support format for those access tokens is the JWT one and the access token in the screenshot does not seem to be a JWT.

You should try to get an access token for that API manually through the Test section in the API (https://auth0.com/docs/apis#how-to-configure-an-api-in-auth0) and see if the issue persists.

In terms of obtaining access tokens for custom API’s from the applications themselves the flow will vary depending on application type so you should check the most adequate flow for you from (https://auth0.com/docs/api-auth).