I'm trying to set up Auth0 authentication. When I try to send an HTTP request to my Django backend API (also protected by Auth0) I get an 401 (Unauthorized error). I managed to narrow down the problem to the access token submission.
When I try to send the HTTP request using axios from my react frontend if I console log the access token it says undefined. And the request doesn't work. Meanwhile if I Just render the access token variable I can display it on my View and if I copy it from there and send the request using Postman everything works just fine. Any idea why this is happening? Many thanks.
--EDIT--
I've found out that the error occurs after reloading while being logged in. The first time you login the GET request works as expected. So I'm assuming the error in in the componentDidMount() in the App.js class but can't figure out why.
async componentDidMount() {
const token = auth0Client.getAccesstoken();
const header = {
headers: { Authorization: `Bearer ${token}` }
};
console.log(token);
const questions = (await axios.get(
"http://localhost:8000/api/question",
header
)).data;
this.setState({
questions
});
}
class App extends Component {
async componentDidMount() {
if (this.props.location.pathname === "/callback") return;
try {
await auth0Client.silentAuth();
this.forceUpdate();
} catch (err) {
if (err.error !== "login_required") console.log(err.error);
}
}
render() {
return ( ...
//If I render it like this on JSX I can display it copy it and use it over Postman
<p>{auth0Client.getAccesstoken()}</p>