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.