【问题标题】:How to use a next-auth jwt in relay-nextjs?如何在 relay-nextjs 中使用 next-auth jwt?
【发布时间】:2021-08-06 02:35:33
【问题描述】:

我正在尝试将next-authrelay-nextjs 一起使用。我根据a hasura jwt example 设置next-auth,并根据the official docs 设置relay-nextjs。我想在发送到 GraphQL 端点的relay-nextjs Authorization 标头中传递一个next-auth jwt Bearer 令牌。

  1. next-auth 提供了一个getSession 方法。 Under the hood,这个requests 是一个服务器端点。

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

我的问题是getSessionserverSideProps 中为空:

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-nextjsnext-auth 回调之前执行。

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

【问题讨论】:

    标签: next.js relay next-auth


    【解决方案1】:

    好的,这比我想象的要容易得多。做吧:

    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

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2021-09-09
      • 2021-10-27
      • 2022-07-22
      • 2021-10-18
      • 2018-06-26
      • 2021-10-26
      • 2021-11-12
      • 2023-02-01
      相关资源
      最近更新 更多