reactjs - 如何使用apollo Reactjs客户端刷新firebase IdToken

标签 reactjs firebase firebase-authentication apollo react-apollo

我正在 ReactJS 中使用 Apollo 客户端与 GraphQL API 进行通信。我们使用 Firebase 身份验证和 JWT 来确保我们的 API 不会向公众公开私有(private)数据,但问题是 Firebase token 每隔一小时左右就会过期。

当用户登录并在请求 header 上使用它时,我当前正在保存 IdToken 本地存储,但是当 token 过期时,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 完成之前完成,因此它也不起作用

最佳答案

将其设为自定义链接而不是自定义获取。

import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
import firebase from 'firebase/app'
import 'firebase/app'
import { setContext } from 'apollo-link-context'
const authLink = setContext((_, { headers }) => {
  //it will always get unexpired version of the token
  return firebase
    .auth()
    .currentUser.getIdToken()
    .then((token) => {
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : ''
        }
      }
    })
})
const link = ApolloLink.from([authLink, ...{/**ur other links */}])

const client = new ApolloClient({
  ssrMode: typeof window !== 'undefined',
  cache: new InMemoryCache().restore({}),
  link
})

关于reactjs - 如何使用apollo Reactjs客户端刷新firebase IdToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662968/

相关文章:

reactjs - Typescript:如何在 React 中为历史对象添加类型检查?

javascript - Firebase:使用异步调用作为 HTTP 触发器的一部分而不会超时?

firebase - Flutter的Firebase教程错误

javascript - 在 Firebase Microsoft 帐户身份验证中从用户获取电子邮件

reactjs - 使用 Hooks 在功能组件中 react 导航标题

javascript - react 选择映射问题

android - Firebase Auth (android) 电子邮件验证需要一些建议

javascript - 如何从 Firebase 管理员获取 Facebook ID?

reactjs - React Typescript 故事书使用 onChange callBack 然后 setState 值 backTo Input 实现自定义输入组件

firebase - Firebase Cloud Firestore 中的非规范化是什么?