使用中间件+next-auth保护next js中的路由

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

如果我没有经过身份验证,请尝试使用 NextJS 中间件保护某些路由,我正在使用 next-auth 进行身份验证,从文档中可以看出,middleware.ts 文件应该是这样的

export { default } from "next-auth/middleware";

export const config = {
    matcher: "/room/:id*"
};

问题是,即使我通过身份验证并尝试进入房间路线,它也会将我重定向到一个页面以再次登录,即使我这样做,它也只会再次将我重定向回来,现在有点像循环。我不知道我可能做错了什么。有谁知道这可能是什么原因造成的?

这是我的下一个身份验证 API :

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaClient } from "@prisma/client";
import { generateRandomString } from "@/utils/random";

const prisma = new PrismaClient();

const handler = NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID!,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
            authorization: {
                params: {
                    prompt: "consent",
                    access_type: "offline",
                    response_type: "code"
                }
            }
        })
    ],
    secret: process.env.JWT_SECRET!,
    callbacks: {
        async signIn({ user, profile }) {
            const existingUser = await prisma.user.findUnique({
                where: { email: user.email! }
            });

            if (!existingUser) {
                const randomSuffix = generateRandomString();
                const firstName = user.name?.split(" ")[0].toLocaleLowerCase();
                await prisma.user.create({
                    data: {
                        email: user.email!,
                        name: user.name!,
                        username: `${firstName}#${randomSuffix}`,
                        image: user.image || profile?.image || null
                    }
                });
            }

            return true;
        },

        async jwt({ token, user }) {
            if (user) {
                token.id = user.id;
            }

            return token;
        }
    }
});

export { handler as GET, handler as POST };
reactjs typescript next.js middleware next-auth
1个回答
0
投票

也许将你的匹配器更改为这个

export const config = {
    matcher: "/room/*"
};
© www.soinside.com 2019 - 2024. All rights reserved.