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 (APIs) 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 (Authentication and Authorization Flows).

1 Like

I am experiencing this same issue with @auth0/auth0-react 1.12.1 with same tech stack.

How was this issue fixed?

My Issue was passing the Promise object instead of waiting for the promise to be fulfilled and then passing the access token returned by the Promise.

I needed to await a call to getAccessTokenSilently() in an async function and then set a local state variable for my access token once it returned.

image