gpt4 book ai didi

reactjs - 如果 Apollo GraphQL token 无效或已过期,则 NextAuth.js 注销

转载 作者:行者123 更新时间:2023-12-03 20:24:03 25 4
gpt4 key购买 nike

在尝试访问后端(Apollo GraphQL)时清除 NextAuth.js session 的最佳方法是什么,并且由于 token 已过期或无效而返回 401?
我想到了 errorLinksignout ,但据我所知 signout 不能在 getServerSideProps 的服务器端使用,而只能在客户端使用。
推荐的方法是什么?有没有其他方法可以实现中间件来处理这种情况?
这将是我试图实现的 errorLink 的概念证明,代码被捕获在 if 中,但我不能将 signOut() 用作 it's only available client-side

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}` : '' },
}),
]),
});
}
谢谢

最佳答案

正如 Noah 和 Yog 告诉你的,没有办法在服务器端做到这一点,因为 signOut 必须清除客户端的状态。所以这就是我将如何做到的:

function createApolloClient(session) {
return new ApolloClient({
cache: new InMemoryCache(),
ssrMode: typeof window === 'undefined',
link: from([
createUploadLink({
uri: GRAPHQL_URI,
credentials: 'same-origin',
headers: { Authorization: session?.accessToken ? `Bearer ${session.accessToken}` : '' },
}),
]),
});
}
然后,在您的 getServerSiderProps 中:
export const fetchServerSideProps = (
initializeApollo: (context: SessionBase | null) => ApolloClient<NormalizedCacheObject>
): GetServerSideProps => async (context) => {
const session = await getSession(context);
const apolloClient = initializeApollo(session);
try {
// Fetch anything from GraphQL here

return {
props: {
// add your required page props here
session,
},
};
} catch {
// Token invalid or expired error (401) caught here, so let's handle this client-side.
return { props: { session: null } };
}
};
最后,您的页面将如下所示:
const withAuth = <P extends { session: Session | null }>(Page: NextPage<P>) => (props: P): JSX.Element | null => {
if (!props.session) {
// Clear session and redirect to login
signOut({ callbackUrl: '/login' });
return null;
}

return <Page {...props} />;
};

const Page: NextPage<P> = (props) => (
<p>This should be shown ONLY if the user is logged in</p>
);

export default withAuth(LoggedInPage);

关于reactjs - 如果 Apollo GraphQL token 无效或已过期,则 NextAuth.js 注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64953673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com