401 error when calling a protected API

I’m having a pretty persistent issue that when I try and hit a protected API, I’m getting a 401 error.

I have a SPA and am using the auth0-react package.

Auth0Provider code:

const audience = process.env.SERVER_URL;

    <Auth0Provider
      domain={process.env.AUTH0_DOMAIN}
      clientId={process.env.AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience,
        useRefreshTokens: true,
      }}
    >
      <App />
    </Auth0Provider>

Access Token Fetch code:

import { useAuth0 } from "@auth0/auth0-react";
  const { getAccessTokenSilently } = useAuth0();

const accessToken = await getAccessTokenSilently({
          authorizationParams: {
            audience: process.env.SERVER_URL,
          },
        });

Client code to call the API

        const options = {
          method: "GET",
          url: "/api/heaList",
          headers: {
            "content-type": "application/json",
            Authorization: `Bearer ${accessToken}`,
          },
        };

        const heaListResponse = await axios.request(options);

Server validation code:

const { auth } = require("express-oauth2-jwt-bearer");

const jwtCheck = auth({
  audience: process.env.SERVER_URL,
  issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}/`,
  tokenSigningAlg: "RS256",
});

app.use(jwtCheck);


Application settings:

  • Application Type: Single Page Application
  • Token Endpoint Authentication Method: None
  • Allow Cross-Origin Authentication: True
  • Rotation: True
  • Reuse Interval: 10
  • Absolute Expiration: True
  • Absolute Lifetime: 2592000
  • Inactivity Expiration: True
  • Inactivity Lifetime: 1296000

API Settings:

  • Token Expiration: 86400
  • Token ExpirationFor Browser Flows: 7200
  • Signing Algorithm: RS256
  • Allow Skipping User Consent: True

Rest of settings are false


I have verified the following through debugging:

  • The process.env.SERVER_URL matches the audience of the protected server.

  • API is using RS256 signing algorithm

  • The access code that is produced is valid when I check with jwt.io. It is not expired, the “iss” matches the Auth0 domain, the API audience is included in the “aud” array.

I’m pretty lost lost as to what to try next, so any help is appreciated.

1 Like

Hi @daniel.meyer,

Welcome to the Auth0 Community!

Is there a more verbose error message? Sometimes the error will include what aspect of the request/token is causing the 401.

Could you please provide a sample token so we can take a look? You can omit sensitive data.

Thanks!

Sure thing. I’ve pasted the message below:

Bearer realm="api", error="invalid_token", error_description="Failed to fetch authorization server metadata"

Sample token is below:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlJWYTgzRG5Nclh0WUVORUJhanZ5RyJ9.eyJpc3MiOiJodHRwczovL2Rldi1icTIzY3FrYWY4MmhxM2x3LnVzLmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHw2M2U5ZDViNTc0ZWI4OTI4ZTBiNDcwMzQiLCJhdWQiOlsiaHR0cHM6Ly9yZWxheS1wb3dlci1tYXBwaW5nLWFwaS5vbnJlbmRlci5jb20iLCJodHRwczovL2Rldi1icTIzY3FrYWY4MmhxM2x3LnVzLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE2ODE3MDIyNDQsImV4cCI6MTY4MTc4ODY0NCwiYXpwIjoiWXJLZG5sbXJOWWpMZk96YTJzVXFMcXQwdHUxamhRMEwiLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGVtYWlsIn0.OK3NZ05Fi8olqSLsAomhKsW0l3IzzGFvRl7-wzc_TxmIihNKshAzT-BspJ4Aqa_nNFLw1gVGRSeLvlm1coWuffQfjuGFPnZ_hQxhe-fYQfiVHA254uy06k3R0ilUvuIaoO6rwuc70WZ0XVj2f79BrqEV7tKyq0qVOdGRFRTpQT0Ws-a_JEelbg0IqFzhT87r5it7POw_mvHuZdc1QlQxTjZ-Zvz1Ru5VHhIDZUKKAyW769wC0tc7JDzLakGS-bD3s-RtH1u55SUrkt-x7HqKKPi6_h9ppdVURGvgAh_nlA7dE45rKsGIdJiUuZJwo9CWDG9LrBn3aGOzQCpmBtTeMg

@daniel.meyer,

This error suggests that your API isn’t able to request the auth metadata to validate the token.

Can you confirm the issuerBaseURL is correct? You can send it to me in a DM and I’ll have a look.

1 Like

Just direct messaged you

We’re running into a similar issue but only when deploying the API with IISNode on a Windows IIS server.

We’re using the same RS256 signing algo and have confirmed that this works via localhost.

The problem comes up when we host it with a domain name served to us via the IIS Server, and try to access a protected API route using the domain name.

When running a localhost version of said API and trying to hit it via http://localhost:3001, it accepts the token and makes the authentication call⁠.

@kkim,

I never heard a final resolution on this, but I think it was the result of an error in the issuer base url.

If that’s not the issue with you, please open a new topic in the #help category.

3 Likes

hey past me. im writing this response in case future me forgets and comes back here, a third time. or in case someone else has this issue w/ IISNode in their hosting stack.

Root Issue
we have our IIS node looking at a specific build folder, but our custom web.config was kept in the src directory and not part of the build process.

Solution
move the web.config over.
And in case your issue is on the config stuff; we had to update our location node’s system.webServer child-node to add an iisnode handler. that’s all I’ll say on the matter.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.