简体   繁体   English

Next.js / NextAuth:为什么我无法在 API 路由中访问 session

[英]Next.js / NextAuth: Why can't I access session in API route

I'm new to Next.js and even newer to NextAuth, so I may be missing something obvious.我是 Next.js 的新手,甚至是 NextAuth 的新手,所以我可能遗漏了一些明显的东西。 I'm using the next-auth email provider as a magic link.我正在使用 next-auth email 提供程序作为魔术链接。 I am able to authenticate and redirect.我能够进行身份验证和重定向。 I can see the cookies in the Application tab of the Chrome dev tools.我可以在 Chrome 开发工具的“应用程序”选项卡中看到 cookies。 I can console log the session in my home page getServerSideProps() like so:我可以在我的主页getServerSideProps()中控制台记录 session,如下所示:

const session = await unstable_getServerSession(context.req, context.res, authOptions)

All of this is working fine...but then when I hit a protected route, the session is null and I get a 401. Here is partial code for a protected route:所有这些都工作正常......但是当我到达受保护的路线时,session 是 null,我得到 401。这是受保护路线的部分代码:

import prisma from 'Utilities/PrismaClient'
import { logDBError } from 'Utilities'
import { unstable_getServerSession } from 'next-auth/next'
import { authOptions } from 'pages/api/auth/[...nextauth]'

export default async function handler (req, res) {
  const session = await unstable_getServerSession(req, res, authOptions)
  console.log(`SESSION_FROM_BOARD_ROUTE: ${JSON.stringify(session)}`) // SESSION_FROM_BOARD_ROUTE: null
  const token = await getToken({ req })

  if (!session) {
    console.log(401)
    return res.status(401).json({ board: {}, tasks: [] })
  }
...
// GET
// POST
// etc, etc.
}

Here is my [...nextauth].ts file:这是我的[...nextauth].ts文件:

// src/pages/api/auth/[...nextauth].ts:

import NextAuth from 'next-auth'
import EmailProvider from "next-auth/providers/email";
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import prisma from 'Utilities/PrismaClient'
import type { NextAuthOptions } from 'next-auth'

export const authOptions:  NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD
        }
      },
      from: process.env.EMAIL_FROM
    }),
  ],
}
export default NextAuth(authOptions);

Here is the page that makes the API request (handleFetchData)这是发出 API 请求的页面 (handleFetchData)

import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import Board from 'Components/Screens/Board/Board'
import { useRouter } from 'next/router'
import axios from 'axios'
import { getBaseUrl } from 'Utilities'
import { hydrateTasks } from 'Redux/Reducers/TaskSlice'

const BoardPage = (props) => {
  const router = useRouter()
  const dispatch = useDispatch()

  useEffect(() => {
    async function handleRouteChange() {
      const { boardId } = router.query
      const { board, tasks } = await handleFetchData({ boardId })
      dispatch(hydrateTasks({ board, tasks }))
    }
    handleRouteChange()
  }, [router])

  return (
    <Board {...props}/>
  )
}

const handleFetchData = async ({boardId, req}) => {
  const baseUrl = getBaseUrl(req)
  return axios.get(`${baseUrl}/api/board/${boardId}`, {
    withCredentials: true
  })
    .then(({data}) => data)
    .catch(err => { console.log(err)})
}

export async function getServerSideProps ({ query, req }) {
  const { boardId } = query
  const { board, tasks}  = await handleFetchData({boardId, req}) ?? {}
  return { props: { board, tasks } }
}

export default BoardPage

Thank you in advance.先感谢您。

...well folks, I believe I found my answer here on Stack Overflow: https://stackoverflow.com/a/69058105/1500241 One must explicitly set cookies when making an HTTP request on the server side! ...好吧,我相信我在 Stack Overflow 上找到了我的答案: https://stackoverflow.com/a/69058105/1500241在服务器端发出 HTTP 请求时,必须明确设置 cookies!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM