如何使用Apollo Reactjs客户端刷新Firebase IdToken

问题描述 投票:4回答:1

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

我目前在用户登录并在请求标头上使用IdToken localstorage时将其保存,但是当令牌到期时,graphql返回Non Authorized错误。我也尝试过从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')
};

但是在firebase.auth.onAuthStateChanged完成之前获取已完成,所以它也不起作用

reactjs firebase firebase-authentication apollo react-apollo
1个回答
0
投票

将其设置为自定义链接,而不是自定义提取。

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
})
© www.soinside.com 2019 - 2024. All rights reserved.