0

我正在尝试使用next-authwith relay-nextjs。我next-auth按照hasura jwt 示例relay-nextjs和官方文档进行设置。我想在发送到 GraphQL 端点next-auth的 Authorization 标头中传递一个 jwt Bearer 令牌。relay-nextjs

  1. next-auth提供了一种getSession方法。在幕后,这会请求一个服务器端点。

  2. relay-nextjs提供了serverSideProps一个withRelayHoC 的属性。您将页面组件传递给withRelay. 您添加一个函数serverSideProps,它将向页面的中继环境发送一个令牌。

我的问题getSession是 null inside 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。cookie 不匹配。他们会这样做,直到最后一个点之后的这一部分,每个请求都会改变。

session-token=xxxx.xxxxxxxx.xxxxx

我通过调试器运行它,它看起来像在回调relay-nextjs之前执行。next-auth

我现在尝试的一种方法是将next-auth令牌存储在数据库中,然后运行 ​​prisma 查询而不是getSession. 欢迎任何意见。

4

1 回答 1

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/77012bc00cd4247ee633777916ece31976b2f477/src/server/routes/session.js#L25

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

于 2021-05-16T22:35:36.373 回答