带有 HTTPS 的 getServerSideProps 中的 nextjs 和 next-auth getSession() 不起作用

nextjs & next-auth getSession() in getServerSideProps with HTTPS not work

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

正常吗?我试了很多次。

如果使用HTTPS,我会得到它。我无法在 getServerSideProps

中使用 getSession()
__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
  2. 中设置了 NEXTAUTH_URL
  3. 我知道我可以在 getInitialProps 中获取 getSession() 但是我需要 get session.user.id 来使用 prisma 获取数据库,同时 prisma 需要 运行 in getServerSideProps

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

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

内部 next-auth 将处理会话,而不管 httphttps

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

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

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

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

提供的反应挂钩
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()
}