'我使用next-auth.js与凭据作为我的登录提供者和Mongodb作为我的后端。为了保护next.js中的页面,我试图将next. auth.js与next.js中间件集成在一起。参考链接
我遇到的问题是当用户注销时,中间件正确地路由到登录页面。但是在成功登录后,用户将再次重定向到登录页面。我错过了什么?
middleware.ts
`export { default } from 'next-auth/middleware';
export const config = { matcher: ['/','/profile','/jadwal','/biodata','/learn'] };`
[...nextauth].ts
`import { compare } from 'bcryptjs';
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { connectToMongoDB } from '../../../lib/mongodb';
import User from '../../../models/user';
import { IUser } from '../../../types';
const options: NextAuthOptions = {
providers: [
CredentialsProvider({
id: "credentials",
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
await connectToMongoDB().catch(err => { throw new Error(err) })
const user = await User.findOne({
email: credentials?.email
}).select("+password")
if (!user) {
throw new Error("Email dan password tidak ditemukan !")
}
const isPasswordCorrect = await compare(credentials!.password, user.password)
if (!isPasswordCorrect) {
throw new Error("Email dan password tidak ditemukan !")
}
return user
}
})
],
pages: {
signIn: "/login"
},
session: {
strategy: "jwt"
},
callbacks: {
jwt: async ({ token, user }) => {
user && (token.user = user)
return token
},
session: async ({ session, token }) => {
const user = token.user as IUser
session.user = user
return session
}
}
}
export default NextAuth(options)
`
'我用"next"^ 13.2.4","next-auth"^ 4.20.1",">
指定callbackUrl
callbackUrl指定用户登录后将被重定向到哪个URL。默认为从开始登录的页面URL.
import { signIn } from "next-auth/react";
//...
signIn("credentials", {
email,
password,
callbackUrl: '/'
}
这将在signIn操作之后将用户重定向到/
url。