使用NextJs和Next-Auth时,getServerSession()在API路由中返回空值

hivapdat  于 2023-02-22  发布在  其他
关注(0)|答案(1)|浏览(200)

我是NextJS和Next-Auth的新手。我正在尝试写一个安全的API路由,只有当用户登录时才可用。我成功地使用useSession()访问了客户端的会话,但是当我尝试在api路由中实现逻辑时,会话总是返回null。我尝试从文档中复制最简单的示例。我错过了什么吗?
下面是我在src/pages/api/users/getUser.ts中的路径:

import { getServerSession } from 'next-auth/next'
import { authOptions } from '../auth/[...nextauth]'
import { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const session = await getServerSession(req, res, authOptions)
  console.log('session', session)

  if (session) {
    res.send({ content: 'SUCCESS' })
  } else {
    res.send({ error: 'ERROR' })
  }
}

下面是我在src/pages/api/auth/[... nextauth].ts中的身份验证选项

import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import prisma from '../../../../prisma/db/prismadb'

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID || '',
      clientSecret: process.env.GITHUB_SECRET || '',
    }),
  ],
  pages: {
    signIn: '/',
    signOut: '/',
  },
}

导出默认的下一个身份验证(身份验证选项)
以下是我的依赖项:

"dependencies": {
    "@next-auth/prisma-adapter": "^1.0.5",
    "@next/font": "13.1.6",
    "@prisma/client": "^4.10.1",
    "@types/node": "18.11.19",
    "@types/react": "18.0.27",
    "@types/react-dom": "18.0.10",
    "axios": "^1.3.2",
    "dotenv-cli": "^7.0.0",
    "eslint": "8.33.0",
    "eslint-config-next": "13.1.6",
    "next": "13.1.6",
    "next-auth": "^4.19.2",
    "prisma": "^4.9.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "styled-components": "^5.3.6",
    "typescript": "4.9.5"
  },
  "devDependencies": {
    "@types/styled-components": "^5.1.26"
  }
au9on6nz

au9on6nz1#

在我的例子中,当NEXTAUTH_URL是127.0.0.1并且向localhost请求API时,会话为空。
因此,我通过匹配NEXTAUTH_URL和请求URL解决了这个问题。

相关问题