在Apollo Server上下文中获取NextAuth.js用户会话



我的web应用程序正在使用:

  • NextJS
  • NextAuth.js
  • 阿波罗服务器

我在我的应用程序中设置了一个NextAuth,我可以很好地登录。

问题来自于试图在Apollo上下文中访问用户的会话。我希望将用户会话传递到每个解析器。下面是我当前的代码:

import { ApolloServer, AuthenticationError } from "apollo-server-micro";
import schema from "./schema";
import mongoose from "mongoose";
import dataloaders from "./dataloaders";
import { getSession } from "next-auth/client";
let db;
const apolloServer = new ApolloServer({
schema,
context: async ({ req }) => {
/*
...
database connection setup

...
*/
// get user's session
const userSession = await getSession({ req });
console.log("USER SESSION", userSession); // <-- userSession is ALWAYS null

if (!userSession) {
throw new AuthenticationError("User is not logged in.");
}
return { db, dataloaders, userSession };
},
});
export const config = {
api: {
bodyParser: false,
},
};
export default apolloServer.createHandler({ path: "/api/graphql" });

问题是,会话(userSession)始终为空,即使我登录(并且可以从适当的NextJS API路由获得会话)。我的猜测是,因为NextAuth函数用于获得会话,getSession({ req })正在传递req——这是由Apollo Server Micro提供的,而不是来自NextJS (NextAuth正在期待)。我做了很多搜索,但找不到有同样问题的人。任何帮助都非常感激!

我有这个问题,我发现这是因为阿波罗GraphQL游乐场。

操场不发送没有"request.credentials": "include"的凭据。

我的NextAuth/GraphQL API是这样的:

import { ApolloServer } from "apollo-server-micro";
import { getSession } from "next-auth/client";
import { typeDefs, resolvers } "./defined-elsewhere"
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const session = await getSession({ req });
return { session };
},
playground: {
settings: {
"editor.theme": "light",
"request.credentials": "include",
},
},
});

希望这对你有用!

我刚刚遇到了类似的事情。我不是100%确定,因为很难知道确切的细节,因为上面的示例代码没有显示在会话作为null通过之前,您如何从客户端与apollo交互。然而,我相信你可能会从getStaticProps内部进行API调用,这会导致静态代码生成并在构建时运行-即当没有这样的用户上下文/会话可能存在时。

见https://github.com/nextauthjs/next-auth/issues/383

The getStaticProps method in Next.js is only for build time page generation (e.g. for generating static pages from a headless CMS) and cannot be used for user specific data such as sessions or CSRF Tokens.

我也不知道为什么你被否决了——这似乎是一个合理的问题,即使答案大多是标准的rtm:)。我以前也在这里发生过——你赢了一些,也输了一些:)干杯

我试图在我的ApolloServer context中获得当前登录用户的会话信息,但从getSession()函数获得null作为响应。因此,我创建了自己的函数,从apollo服务器上下文的NextAuth端点获取会话数据。

src/index.ts

context: async ({ req }): Promise<GraphQLContext> => {
const session = await getServerSession(req.headers.cookie);
return { session: session as Session, prisma };
}

getServerSession.ts

import fetch from "node-fetch";
export const getServerSession = async (cookie: string) => {
const res = await fetch('http://localhost/api/auth/session',{
headers: { cookie: cookie },
});
const session = await res.json();
return session;
};

我希望这能帮助到每一个试图在apollo服务器上下文中获取会话信息的人,同时使用next-auth进行身份验证。

最新更新