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

scx*_*992 12 reactjs next.js next-auth

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

\n

这正常吗?我尝试了很多次。

\n

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

\n
__Secure-next-auth.callback-url\n__Secure-next-auth.session-token\n__Host-next-auth.csrf-toke\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
next-auth.callback-url\nnext-auth.session-token\nnext-auth.csrf-token\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

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

\n

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

\n
import { getSession } from 'next-auth/client';\n\nexport default function Home(props) {\n  console.log(props.session);\n  return (\n    <div>\n      <h1>Server Side Rendering</h1>\n    </div>\n  );\n}\nexport async function getServerSideProps(context) {\n  return {\n    props: {\n      session: await getSession(context),\n    },\n  };\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

备注\xef\xbc\x9a

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

raz*_*boy 21

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

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

内部next-auth将处理会话,无论httphttps

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

完整的工作示例在这里:

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

页面/_app.js

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

export default function App({ Component, pageProps }) {
  return (
    <Provider session={pageProps.session}>
      <Component {...pageProps} />
    </Provider>
  )
}
Run Code Online (Sandbox Code Playgroud)

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

页面/index.js

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

export async function getServerSideProps(ctx) {
  return {
    props: {
      session: await getSession(ctx)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的组件内部使用由提供的反应钩子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>
}
Run Code Online (Sandbox Code Playgroud)

在服务器端的 api 路由中:

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

export default async (req, res) => {
  const session = await getSession({ req })
  res.end()
}
Run Code Online (Sandbox Code Playgroud)