首页 > 解决方案 > 处理自定义 apollo graphql 后端的 firebase 初始化延迟和 id 令牌

问题描述

目前,当我使用 firebase 对用户进行身份验证时,我会将他们的身份验证令牌存储起来localStorage以供以后连接到我的后端,如下所示:

const httpLink = new HttpLink({uri: 'http://localhost:9000/graphql'})

const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization token to the headers
  const token = localStorage.getItem(AUTH_TOKEN) || null
  operation.setContext({
    headers: {
      authorization: token ? `Bearer ${token}` : ''
    }
  })
  return forward(operation)
})

const authAfterware = onError(({networkError}) => {
  if (networkError.statusCode === 401) AuthService.signout()
})

function createApolloClient() {
  return new ApolloClient({
    cache: new InMemoryCache(),
    link: authMiddleware.concat(authAfterware).concat(httpLink)
  })
}

我的问题是,一旦令牌过期,我就无法刷新令牌。所以我尝试使用以下方法为 apollo 设置授权令牌:

const httpLink = new HttpLink({uri: 'http://localhost:9000/graphql'})

const asyncAuthLink = setContext(
  () => {
    return new Promise((success, reject) => {
      firebase.auth().currentUser.getToken().then(token => {
        success({
          headers: {
            authorization: token ? `Bearer ${token}` : ''
          }
        })
      }).catch(error => {
        reject(error)
      })
    })
  }
)

const authAfterware = onError(({networkError}) => {
  if (networkError.statusCode === 401) AuthService.signout()
})

function createApolloClient() {
  return new ApolloClient({
    cache: new InMemoryCache(),
    link: asyncAuthLink.concat(authAfterware.concat(httpLink))
  })
}

这在用户第一次进行身份验证时有效,但是一旦用户刷新页面,当我的 graphql 查询发送到我的后端时,firebase 就不再初始化,因此令牌不会随它一起发送。有没有办法我可以异步等待firebase.auth().currentUser所以这会起作用?还是我应该完全采取另一种方法?据我所知(100% 肯定)currentUser.getIdToken仅在当前令牌不再有效时才进行网络调用。我认为这是可以接受的,因为在令牌无效的情况下,后端无论如何都无法响应,所以我需要等待令牌刷新才能继续。

我想到的其他一些想法:

谢谢!

标签: reactjsfirebasefirebase-authenticationapolloapollo-link

解决方案


推荐阅读