前端查询AuthenticatedItem返回null,GraphQL Playground功能正常
问题排查与解决方案
核心问题定位
你遇到的是前端ApolloClient请求未携带认证会话信息,导致Keystone后端无法识别已登录用户,所以authenticatedItem返回null。尽管登录mutation成功,但会话凭证没有在后续查询中正确传递。
具体排查步骤
1. 检查ApolloClient的凭证配置
确保ApolloClient实例开启了credentials: 'include',这样才会自动携带登录后的Cookie(Keystone默认用Cookie存储会话):
// apollo-client.js 或类似配置文件 import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; const httpLink = createHttpLink({ uri: '/api/graphql', // 你的Keystone GraphQL端点 credentials: 'include', // 关键:开启凭证携带 }); const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), });
2. 验证跨域配置(如果前后端域名不同)
如果前端和Keystone后端不在同一域名下,需要在Keystone配置中设置CORS允许携带凭证:
// keystone.config.js export default { server: { cors: { origin: ['http://你的前端域名'], credentials: true, // 必须设为true }, }, // 其他配置... };
3. 确认登录后的Cookie存储
登录成功后,打开浏览器开发者工具(Application -> Cookies),检查是否存在Keystone生成的会话Cookie(通常名为keystone-session)。如果没有,说明登录mutation的响应没有正确设置Cookie,可能是Keystone的认证配置有误。
4. 检查查询的上下文传递
确保你的查询没有覆盖默认的凭证设置。比如使用useQuery时,不要手动设置context里的credentials为omit:
// 错误示例:会覆盖全局配置 const { data } = useQuery(GET_AUTHENTICATED_USER, { context: { credentials: 'omit' } }); // 正确示例:使用全局配置,或显式设置为'include' const { data } = useQuery(GET_AUTHENTICATED_USER, { context: { credentials: 'include' } });
5. 验证Keystone的认证会话配置
检查Keystone的用户认证配置,确保启用了会话存储,比如使用默认的Cookie会话:
// keystone.config.js import { config } from '@keystone-6/core'; import { statelessSessions } from '@keystone-6/core/session'; const session = statelessSessions({ secret: process.env.SESSION_SECRET, // 必须设置环境变量 secure: process.env.NODE_ENV === 'production', // 生产环境开启secure sameSite: 'lax', }); export default config({ session, // 其他配置... });
额外调试技巧
- 在浏览器开发者工具的Network标签下,查看查询
authenticatedItem的请求头,确认是否包含Cookie字段,且值为登录后的会话Cookie。 - 如果请求头没有Cookie,检查ApolloClient的配置是否正确,或者是否有其他拦截器修改了请求头。
内容的提问来源于stack exchange,提问作者Mikel Sigler
相关产品推荐
相关产品推荐

