我正在尝试将 next-auth
与 relay-nextjs
一起使用。我为每个 a hasura jwt example 设置 next-auth
,每个 the official docs 设置 relay-nextjs
。我想在发送到 GraphQL 端点的 next-auth
Authorization 标头中传递一个 relay-nextjs
jwt Bearer 令牌。
next-auth
提供了一个 getSession
方法。 Under the hood,这 requests 一个服务器端点。
relay-nextjs
提供 serverSideProps
HoC 的 withRelay
属性。您将页面组件传递给 withRelay
。您向 serverSideProps
添加一个函数,该函数将向页面的 Relay 环境发送令牌。
我的问题是 getSession
在 serverSideProps
内为空:
serverSideProps: async (ctx) => {
const { getSession } = await import('next-auth/client');
// This is an example of getting an auth token from the request context.
// If you don't need to authenticate users this can be removed and return an
// empty object instead.
const token = await getSession();
return { token };
}
如果我可以在此处获取令牌,则它在 relay-nextjs
中有效。返回字符串工作正常,将其添加到标题中。
应用页面请求中有一个 next-auth
cookie。我根据 getSession
调用的端点检查了它。饼干不匹配。他们这样做,直到最后一个点之后的这部分,它会随着每个请求而改变。
session-token=xxxx.xxxxxxxx.xxxxx
我通过调试器运行它,看起来 relay-nextjs
在 next-auth
回调之前执行。
我现在尝试的一种方法是将 next-auth
令牌存储在数据库中,并运行 Prisma 查询而不是 getSession
。欢迎任何输入。
答案 0 :(得分:0)
好吧,这比我想象的要容易得多。就这样做:
serverSideProps: async (ctx) => {
// This is an example of getting an auth token from the request context.
// If you don't need to authenticate users this can be removed and return an
// empty object instead.
return { token: ctx.req.cookies['next-auth.session-token'] };
}
我在这里跟踪了下一个身份验证代码:
https://github.com/nextauthjs/next-auth/blob/main/src/server/lib/cookie.js#L142
https://github.com/nextauthjs/next-auth/blob/main/src/server/index.js#L66