0

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>
1
  • After doing some more testing it works the first time I login but not if I reload, even though the <p> tag always gets rendered with the token value. Commented Aug 18, 2019 at 19:57

1 Answer 1

1

I would assume that it's an async issue, try:

const token = await auth0Client.getAccesstoken();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Tried that but it didn't work, the problem is still the same. The request fails although the token is there and it only happens while reloading. If I go to a different path on the website and come back there it works, so is only on reload.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.