[英]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 promisegetIdToken
返回一个承诺
firebase.auth()
.signInWithCredential(credential)
.then(async data => {
const jwtToken = await data.user?.getIdToken();
console.log(jwtToken);
})
只需将await
放在之前也可以像这样工作:
await auth().currentUser.getIdToken();
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.