Apollo client + Next.js - 向客户端请求添加授权令牌

Apollo client + Next.js - Adding Authorization token to client request

目标

我想用访问令牌填充我的 Authorization header。我想将该访问令牌存储在 Apollo 缓存中,因为 Auth0 explicitly state not to store access tokens in local storage (I don't know why the Apollo Client docs 似乎认为没问题。

否则,我想安全地存储我的访问令牌,并能够将它添加到每个 Apollo 客户端对 Apollo 服务器的请求中。

const apolloClient = withApollo(({ctx, headers, initialState}) => {
  const cache = new InMemoryCache();

  // Code here to access local cache.

  return new ApolloClient({

    cache,
    link: new HttpLink({
      uri: <apollo server endpoint>,
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Access-Control-Allow-Origin': 'http://localhost:3000/',
        ...headers
      },
      credentials: 'include'
    }),
    typeDefs,
    resolvers
  })
})

class MyApp extends App {
  render() {
    const { Component, pageProps, apollo } = this.props;


    return (
      <ApolloProvider client={apollo}>
        <Component {...pageProps} />
      </ApolloProvider>
    );
  }
}

export default apolloClient(MyApp);

尝试过

其他想法

问题

我找到了问题的解决方案。我只是没有完全理解 Apollo Client 以及如何使用所有必需的包。

解决方案

我使用了 apollo-link-context 库中的 setContext。它是 Apollo Client 提供的 link 库集的一部分,用于在 graphql 操作启动后自定义网络请求。我在 setContext 函数中设置了 header。像这样:

const authLink = setContext((_, { headers }) => {
  // It is also possible to use the local storage method in here.
  const data = cache.readQuery({
    query: ACCESS_TOKEN
  });

  return {
    headers: {
      ...headers,
      authorization: accessToken ? `Bearer ${data.accessToken}` : ""
    }
  }
});

以下是withApollo函数之外的内容。

const httpLink = new HttpLink({
  uri: '<server uri>',
});

下面是withApollo函数里面的内容。

return new ApolloClient({
    cache,
    link: authLink.concat(httpLink),
    typeDefs,
    resolvers
  })

setContext 的文档 here and the docs for the `apollo-link-context' are here