getAccessToken without withAuth

following this guide: https://developer.okta.com/quickstart/?_ga=2.174784354.1113360022.1565196295-15852248.1564059434#/react/nodejs/express

it’s a common practice to create a “service” class for talking to an API so instead of doing this:

async componentDidMount() {
    try {
      const response = await fetch('http://localhost:{serverPort}/api/messages', {
        headers: {
          Authorization: 'Bearer ' + await this.props.auth.getAccessToken()
        }
      });
      const data = await response.json();
      this.setState({ messages: data.messages });
    } catch (err) {
      // handle error as needed
    }
  }

you would do this:

  componentDidMount() {
    FooService.getStuff().then( (stuff) => this.setState({stuff}) );
  }

the only way I have been able to get this working is like so…and there HAS to be a better way to get the bearer token!!!

// TODO there _HAS_ to be a better way to get the access token from storage!!!
        let token = JSON.parse(localStorage.getItem('okta-token-storage')).accessToken.accessToken;
        return axios.get( '/foo', {
            headers: {
                Authorization: 'Bearer ' + token
            }
        }).then((response) => {
            return response.data.stuff;
        });

Did you ever find a solution to this? Experiencing some of the same issues.

Can you take a look at our React sample, which is using useOktaAuth instead of withOktaAuth?

if (authState.isAuthenticated) {
  const accessToken = oktaAuth.getAccessToken();
  fetch(config.resourceServer.messagesUrl, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  })

Hi andreaskouras!

This is a great way to do this in a component based solution, but getAccessToken() does not work as expected once you try to use it in an external JS file (like a service layer). Instead I am having to pull the token myself from local storage. Please advise, here :slight_smile:

In that other thread, you mentioned that getAccessToken does not always work to grab the token from storage. Do you see that this method sometimes works? Under what circumstances?