gpt4 book ai didi

protecting routes in next js with middleware + next-auth(使用中间件+Next-auth保护Next JS中的路由)

转载 作者:bug小助手 更新时间:2023-10-25 14:47:23 30 4
gpt4 key购买 nike



please I am trying to protect some routes with the NextJS middleware if I am not authenticated, I am using next-auth for authentication and from the documentation this is what it says the middleware.ts file should be like

如果我没有通过身份验证,我正在尝试使用NextJS中间件保护一些路由,我正在使用Next-auth进行身份验证,从文档中看,这就是MIDDLEWAR.TS文件应该是什么样子


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

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

The issue rn is even when I am authenticated and I try to go to the room route, it redirects me to a page to sign in again and even when I do that it just redirects me back again, sort of like a loop now. I don't know what I might be doing wrong. Anyone knows what might be causing this ?

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


This is my next-auth API :

这是我的Next-auth接口:


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 };

更多回答
优秀答案推荐
更多回答

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com