5
votes

I am trying to get the Firebase authentication access token within a React Native application so that I can authenticate my API calls to a custom server. The Firebase documentation says I should get this token by using auth().currentUser.getIdToken(); however currentUser returns null.

I've tried to use getIdToken() in multiple areas of the application. I know the access token is generated as I can see it in the logs while using expo (user.stsTokenManager.accessToken).

Why is currentUser returning null and how can I get the accessToken?

4

4 Answers

13
votes

You need to wrap user.getIdToken() inside of firebase.auth().onAuthStateChanged for user to be available. You can then use jwtToken in your header to authenticate your API calls. You need to import your Firebase configuration file for this to work.

let jwtToken = firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      user.getIdToken().then(function(idToken) {  // <------ Check this line
          alert(idToken); // It shows the Firebase token now
          return idToken;
      });
    }
  });
1
votes

Just putting await before will work too just like this:

await auth().currentUser.getIdToken();

0
votes

getIdToken returns a promise

firebase.auth()
        .signInWithCredential(credential)
        .then(async data => {
          const jwtToken = await data.user?.getIdToken();
          console.log(jwtToken);
        })
0
votes

Hook example

Unfortunately, its not reliable to directly get the token. You first have to listen to the authentication state change event which fires upon initialization since its asynchronous.

import {auth} from '../utils/firebase'
import {useState, useEffect} from 'react'

export default function useToken() {
  const [token, setToken] = useState('')
  useEffect(() => {
    return auth().onAuthStateChanged(user => {
      if (user) {
        user.getIdToken(true)
        .then(latestToken => setToken(latestToken))
        .catch(err => console.log(err))
      }
    })
  }, [])
  return token
}

then use like so in your functional component


const token = useToken()

useEffect(() => {
  if (token) {
    // go wild
  }
}, [token])