如何在中间件中获取下一个Auth会话

问题描述 投票:0回答:1

我已经使用 nextAuth 和 next js 4.23.1 创建了一个会话,并且它可以工作,但是我不知道如何在我的中间件中获取会话或令牌,我尝试将处理程序传递给 getSession() 并且不起作用全部。

我可以通过useSession在任何use clinte组件中获取session

我如何在服务器端获取会话和/或令牌,感谢您的帮助

在 api/auth/[..nextauth]/route

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { _AUTH } from "@/app/services/shared/endpoints";

export const handler = NextAuth({
    session: {
      strategy: 'jwt'
    },

    providers: [
      CredentialsProvider({
        async authorize(credentials, req){
            const res  = await fetch(_AUTH._AUTH_LOGIN, {
                method: 'POST',
                body: JSON.stringify({user:{...credentials}}),
                headers: { "Content-Type": "application/json" }
            })
               const user = await res.json()
               if (!user) {
                  return
                } else {
                  return user
                }
            }
        })
    ],
      pages: {
        signIn: '/login',
      }
})
  
export { handler as GET, handler as POST }

中间件

import { handler } from "./app/api/auth/[...nextauth]/route"
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getSession } from "next-auth/react"


export async function middleware(request: NextRequest) {

    const session = await getSession(handler)

    if(session !== undefined || session !== null){
        return NextResponse.redirect(new URL('/empresa/mis-empresas', request.url))
    }
}
 
export const config = {
  matcher: [
    '/empresa/mis-empresas',
  ]
}
reactjs next
1个回答
0
投票

要在服务器端获取会话,您不应直接尝试将 NextAuth 处理程序传递给 getSession。 getSession 函数也可以在服务器端工作,但您需要将请求对象传递给它。

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getSession } from "next-auth/react"

export async function middleware(request: NextRequest) {
    const session = await getSession({ req: request });

    if(session){
        return NextResponse.redirect('/empresa/mis-empresas')
    }
}

getSession 接受一个应该包含 req 属性的对象,该属性代表请求。我删除了 if 语句中不必要的比较。检查 if(session) 应该足以确定是否存在有效会话。确保您的中间件已正确配置和执行。中间件是 Next.js 12 中的新增功能,因此您可能需要参考 Next.js 文档以确保您已正确设置它。

© www.soinside.com 2019 - 2024. All rights reserved.