Reputation: 315
So I have read through several SO questions about this, and read many Auth0 tutorials on this, but I still cannot get the Access Token to work with my custom API.
I have followed the Auth0 SPA tutorial for React. I then followed the "Call Your API from Your Single-Page App" tutorial. I have created an "auth0-authorization-extension-api". I enabled API access to my custom API.
I feel I have done the necessary steps, but I feel I am missing how to request the proper access token from my React client.
My Axios custom hook contains the following code inside a useEffect:
const send = async () => {
try {
await getTokenSilently().then(async (token: string) => {
const config = {
method: method as "GET" | "POST",
withCredentials: true,
data: providedData,
headers: {
Authorization: "Bearer " + token
}
};
const result = await axios(address + uri, config);
});
} catch (error) {
if (!canceled) {
dispatch({ type: "FETCH_FAILURE" });
}
}
};
The access token being sent to my API is not a full jwt, but a string of numbers and letters approximately 35 digits in length.
Every time I get the error UnauthorizedError: jwt malformed
from my custom API.
My audience for the React SPA is http://localhost:3000
, and the API audience is http://localhost:8080
.
Am I missing something simple here or am I looking in the wrong place?
Upvotes: 4
Views: 666
Reputation: 899
Add audience to getTokenSilently authorizationParams:
const send = async () => {
try {
const token = await getAccessTokenSilently({
authorizationParams: {
audience: 'YOUR-API-AUDIENCE',
// ^
},
}).then(async (token: string) => {
const config = {
method: method as 'GET' | 'POST',
withCredentials: true,
data: providedData,
headers: {
Authorization: 'Bearer ' + token,
},
};
const result = await axios(address + uri, config);
});
} catch (error) {
if (!canceled) {
dispatch({ type: 'FETCH_FAILURE' });
}
}
};
and also add to the Auth0Provider authorizationParams
<Auth0Provider
domain={"YOIR-AUTH-DOMAIN"}
clientId={YOIR-CLIENT-ID}
authorizationParams={{
audience: "YOUR-API-AUDIENCE",
// ^
}}
Upvotes: 0
Reputation: 16695
The access token you got is just a pure random string. With Auth0, if you want to a JWT as access token, you have to indicate the audience i.e. the API identifier.
Upvotes: 2