我在ReactJS中使用Apollo Client与GraphQL API通信。我们使用Firebase身份验证及其JWT来确保API不会将私有数据暴露给公众,但问题是Firebase令牌大约每小时过期一次。
我目前在用户登录时将IdToken保存在本地存储中,并在请求标头上使用该令牌,但当令牌过期时,graphql返回未经授权的错误。我还尝试在Apollo的createHttpLink函数上使用customfetch。
const customFetch = async (uri, options) => {
console.log(firebase.auth.currentUser)
if (firebase.auth.currentUser) {
const token = await firebase.auth.currentUser.getIdToken()
localStorage.setItem('token', token)
options.headers.authorization = token;
return fetch(uri, options);
}
else {
firebase.auth.onAuthStateChanged(async (user) => {
if (user) {
console.log('Inside on Auth')
const token = await user.getIdToken()
localStorage.setItem('token', token)
options.headers.authorization = token;
return fetch(uri, options);
}
})
}
console.log('End of Fetch')
};
但是fetch在firebase.auth.onAuthStateChanged完成之前就完成了,所以它也不能正常工作。