简体   繁体   English

在 React Native 中从 Firebase 获取当前用户访问令牌

[英]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.我正在尝试在 React Native 应用程序中获取 Firebase 身份验证访问令牌,以便我可以对对自定义服务器的 API 调用进行身份验证。 The Firebase documentation says I should get this token by using auth().currentUser.getIdToken(); Firebase 文档说我应该使用auth().currentUser.getIdToken();来获取这个令牌auth().currentUser.getIdToken(); however currentUser returns null .但是 currentUser 返回null

I've tried to use getIdToken() in multiple areas of the application.我尝试在应用程序的多个区域使用getIdToken() I know the access token is generated as I can see it in the logs while using expo (user.stsTokenManager.accessToken).我知道访问令牌是生成的,因为我在使用 expo (user.stsTokenManager.accessToken) 时可以在日志中看到它。

Why is currentUser returning null and how can I get the accessToken ?为什么currentUser返回null以及如何获取accessToken

You need to wrap user.getIdToken() inside of firebase.auth().onAuthStateChanged for user to be available.您需要将user.getIdToken()包装在firebase.auth().onAuthStateChanged以便user可用。 You can then use jwtToken in your header to authenticate your API calls.然后,您可以在标头中使用 jwtToken 来验证您的 API 调用。 You need to import your Firebase configuration file for this to work.您需要导入 Firebase 配置文件才能使其正常工作。

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 getIdToken返回一个承诺

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取本机客户端,firebase令牌的响应 - Get react native client, firebase token 如何使用 Firebase react native 获取当前时间戳? - How to get current timestamp with Firebase react native? 如何在Firebase Ionic中获取当前用户和实际访问令牌? - How to get current user and actual access token in Firebase Ionic? 如何从 React Native 中的 firebase 实时数据库获取当前用户数据 - How to get current user data from firebase realtime database in React Native 如何使用本机反应从实时数据库 firebase 获取当前用户信息 - how to get current User's information from realtime database firebase using react native 获取令牌以在react-native中将帖子发布到Firebase数据库 - Get token to call post to firebase database in react-native 如何在React Native中从Firebase Auth中检索用户数据? - how to retrieve users data from firebase auth in react native? React Native Flatlist 搜索从 firebase 用户集合中返回没有值 - React Native Flatlist search returning no values from firebase users collection 如何在本机反应中从 firebase 获得 object - How to get an object from firebase in react native 当前访问令牌已过期时,我如何获取新的访问令牌,谷歌 firebase 身份验证? - How i get new access token when current access token has expired, google firebase auth?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM