如果 Apollo GraphQL 令牌无效或已过期,则 NextAuth.js 注销

Van*_*sie 5 apollo reactjs graphql next.js next-auth

在尝试访问后端(Apollo GraphQL)时清除 NextAuth.js 会话的最佳方法是什么,并且由于令牌已过期或无效而返回 401?

我想到了errorLinkand signout,但据我所知signout不能在服务器端使用getServerSideProps,而只能在客户端使用。

推荐的方法是什么?有没有其他方法可以实现中间件来处理这种情况?

这将是errorLink我正在尝试实现的概念的证明,代码被困在其中,if但我无法使用,signOut()因为它仅在客户端可用

const errorLink = onError(({ graphQLErrors }) => {
   if (graphQLErrors?.[0]?.message === 'Unauthenticated.') {
    // signOut();
  }
});

function createApolloClient(session) {
  return new ApolloClient({
    cache: new InMemoryCache(),
    ssrMode: typeof window === 'undefined',
    link: from([
      errorLink,
      createUploadLink({
        uri: GRAPHQL_URI,
        credentials: 'same-origin',
        headers: { Authorization: session?.accessToken ? `Bearer ${session.accessToken}` : '' },
      }),
    ]),
  });
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Noa*_*nyo 0

这取决于您使用的 Apollo 版本,但假设您使用的是 Apollo 3.0 <= 您可以为您的请求创建 setcontext。

import { setContext } from '@apollo/client/link/context';

const authLink = setContext((_, { headers }) => {
  const token = session?.accessToken ? session.accessToken : ""
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

function createApolloClient(session) {
  return new ApolloClient({
    cache: new InMemoryCache(),
    ssrMode: typeof window === 'undefined',
    link: from([
      authLink,
      errorLink,
      createUploadLink({
        uri: GRAPHQL_URI,
        credentials: 'same-origin'
      }),
    ]),
  });
}
Run Code Online (Sandbox Code Playgroud)

由于signOut()会重新呈现您的应用程序,因此您可以检查上下文以查看它是否具有来自服务器的请求的有效令牌。还没有测试过,但理论上这就是我实现它的方式。