简体   繁体   中英

Get current users access token from Firebase in React Native

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 ?

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;
      });
    }
  });

getIdToken returns a promise

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

只需将await放在之前也可以像这样工作:

await auth().currentUser.getIdToken();

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM