小编Isa*_*isi的帖子

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

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

当用户登录并在请求标头上使用它时,我目前正在保存 IdToken localstorage 但是当令牌过期时,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);
            }
        }) …
Run Code Online (Sandbox Code Playgroud)

firebase apollo reactjs firebase-authentication react-apollo

4
推荐指数
1
解决办法
1064
查看次数