【发布时间】:2020-08-03 05:59:53
【问题描述】:
所以我们正在使用 Apollo 和 GraphQL 创建一个 React-Native 应用程序。我正在使用基于 JWT 的身份验证(当用户同时登录 activeToken 并创建 refreshToken 时),并且想要实现一个流程,当服务器注意到令牌已过期时,令牌会自动刷新。
Apollo-Link-Error 的 Apollo Docs 提供了一个很好的 starting point 来捕获来自 ApolloClient 的错误:
onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case 'UNAUTHENTICATED':
// error code is set to UNAUTHENTICATED
// when AuthenticationError thrown in resolver
// modify the operation context with a new token
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: getNewToken(),
},
});
// retry the request, returning the new observable
return forward(operation);
}
}
}
})
但是,我真的很难弄清楚如何实现 getNewToken()。 我的 GraphQL 端点具有创建新令牌的解析器,但我不能从 Apollo-Link-Error 调用它,对吧?
那么,如果 Token 是在 Apollo 客户端将连接到的 GraphQL 端点中创建的,那么如何刷新 Token?
【问题讨论】:
-
onError 链接在请求后运行。我认为您不能简单地转发再试一次。理想情况下,您可以确定您当前的令牌在前端是否仍然有效,例如通过查看 JWT 中的
exp声明。然后你可以使用这个极好的链接:github.com/newsiberian/apollo-link-token-refresh -
您可以使用
window.fetch调用您的GraphQL enpoint。这需要更多的工作,但对于单个查询来说应该没问题。只需POST到端点,其 JSON 对象包含query和可选的variables和operation。
标签: react-native graphql apollo apollo-client