Hi!
I tried to reproduce the issue today, but for some reason everything went fine for me.
This is what I did after downloading the quickstart project:
- I added the
audience
entry inauth_config.json
- I added the
audience
entry in the render code of theAuth0Provider
inindex.js
:
ReactDOM.render(
<Auth0Provider
domain={config.domain}
client_id={config.clientId}
redirect_uri={window.location.origin}
onRedirectCallback={onRedirectCallback}
audience={config.audience}
>
<App />
</Auth0Provider>,
document.getElementById("root")
);
- I added some crude code in the
Hero.js
view to get a token:
// this is new
import { useAuth0 } from "../react-auth0-spa";
const Hero = () => {
// this is new
const { getTokenSilently,getTokenWithPopup } = useAuth0();
// this is new
const getAccessToken = async function() {
try {
var token = await getTokenSilently({audience:"Test"});
alert(token);
} catch (e)
{
alert(JSON.stringify(e));
}
}
return (
<div className="text-center hero my-5">
<img className="mb-3 app-logo" src={logo} alt="React logo" width="120" />
<h1 className="mb-4">React.js Sample Project</h1>
<p className="lead">
This is a sample application that demonstrates an authentication flow for
an SPA, using <a href="https://reactjs.org">React.js</a>
</p>
<button onClick={() => getAccessToken()}>Let's get an Access Token</button>
</div>
)
};
export default Hero;
In the above code I reference the useAuth0()
export from react-auth0-js
to call the API (this is important, to get the default options), and there’s a button at the bottom that triggers the “getAccessToken()” local function.
I tried putting the audience
as the provider configuration, and that works as expected (the token obtained from both getTokenSilently
and getTokenWithPopup
are for that audience). I also tried not configuring an audience for the provider and instead passing the audience in the calls to getTokenSilently
and getTokenWithPopup
and that also worked as expected.
From the issues you describe, it seems as if at some point there was more than one instance of the Auth0Provider
instead of using the one stored as a React context and get by useAuth0()
.
Would you mind starting fresh and doing the above changes to see if you get a good result? If so, can you spot the differences that caused trouble?