簡體   English   中英

如何使用 apollo Reactjs 客戶端刷新 firebase IdToken

[英]How to refresh firebase IdToken with apollo Reactjs client

我在 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 完成之前獲取完成,所以它也不起作用

將其設為自定義鏈接而不是自定義獲取。

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

我為此使用遞歸,但不確定它是否有任何問題。

firebase.auth.onAuthStateChanged(async (user) => {
    if (user) {
        setToken(user)
    }
})

const setToken = async (user) => {
    const token = await user.getIdToken();
    localStorage.setItem("token", token);

    setTimeout(() => setToken(user), 59000);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM