【问题标题】:nextjs & next-auth getSession() in getServerSideProps with HTTPS not work使用 HTTPS 的 getServerSideProps 中的 nextjs 和 next-auth getSession() 不起作用
【发布时间】:2021-10-26 16:36:36
【问题描述】:

我无法通过 HTTPS 在 getServerSideProps 中使用 getSession()。

正常吗?我试了很多次。

如果使用 HTTPS 我会得到它。我无法在 getServerSideProps 中获取会话()

__Secure-next-auth.callback-url
__Secure-next-auth.session-token
__Host-next-auth.csrf-toke

如果使用 HTTP 并且我可以在 getServerSideProps 中使用 getSession() 就可以了

next-auth.callback-url
next-auth.session-token
next-auth.csrf-token

如何在 getServerSideProps 中的 HTTPS getSession() 上修复它?

我在 http 或 https 上运行相同的代码进行测试

如果使用 http 运行,我可以获得 props.session 如果使用 https 运行,我无法获取 props.session

import { getSession } from 'next-auth/client';

export default function Home(props) {
  console.log(props.session);
  return (
    <div>
      <h1>Server Side Rendering</h1>
    </div>
  );
}
export async function getServerSideProps(context) {
  return {
    props: {
      session: await getSession(context),
    },
  };
}

备注:

  1. 我在.env 中设置了NEXTAUTH_URL
  2. 我知道我可以在getInitialProps 中获取getSession() 但是我需要用prisma获取session.user.id来获取数据库,同时prisma需要在getServerSideProps中运行

【问题讨论】:

  • 您是否配置了NEXTAUTH_URL 环境变量?从控制使用哪个协议的内存中。 next-auth.js.org/configuration/options#nextauth_url
  • @razboy 当然,我试过如果设置NEXTAUTH_URL=http://localhost:3000 并使用HTTP 运行,一切正常。但是如果设置 NEXTAUTH_URL=https://localhost:3000 并使用 HTTPS 运行。我无法在getServerSideProps 中获得任何会话
  • 啊,我认为 Next.js 不会在本地运行 SSL。您可能需要在其前面运行代理或配置自定义服务器。 Http 应该可以用于本地测试。也许你可以部署在某个地方进行 https 测试。
  • 只是一个演示。因为我在我的生产自定义服务器上进行测试,所以我需要使用 SSL 运行。

标签: reactjs next.js next-auth


【解决方案1】:

这种行为是正常的。这些值是next-auth 的内部值。当NEXTAUTH_URLhttps 为前缀时,cookie 将被标记为安全。您可以在此处查看行为:

https://github.com/nextauthjs/next-auth/blob/543f812eb32448044d2aa725b623ca1dedbb68a3/src/lib/jwt.js#L115

无论http 还是https,在内部next-auth 都会处理会话。

要配置客户端会话,您可以按照文档中的示例进行操作:

这里有一个完整的工作示例:

首先配置一个提供者以便在您的组件之间共享会话。

pages/_app.js

import { Provider } from "next-auth/client"

export default function App({ Component, pageProps }) {
  return (
    <Provider session={pageProps.session}>
      <Component {...pageProps} />
    </Provider>
  )
}

如果您还需要在服务器端渲染期间支持身份验证,则需要。

pages/index.js

import { getSession } from "next-auth/client"

export async function getServerSideProps(ctx) {
  return {
    props: {
      session: await getSession(ctx)
    }
  }
}

在你的组件内部使用next-auth提供的react hook

import { useSession } from "next-auth/client"

export default function Component() {
  const [session, loading] = useSession()

  if (session) {
    return <p>Signed in as {session.user.email}</p>
  }

  return <a href="/api/auth/signin">Sign in</a>
}

并且在服务端的api路由中:

import { getSession } from "next-auth/client"

export default async (req, res) => {
  const session = await getSession({ req })
  res.end()
}

【讨论】:

  • 使用getStaticPaths时如何获取会话?那里没有可用的上下文?
猜你喜欢
  • 2022-07-24
  • 2021-11-12
  • 2021-09-09
  • 2023-02-14
  • 1970-01-01
  • 2021-08-06
  • 2022-01-22
  • 2021-10-06
  • 2021-09-27
相关资源
最近更新 更多