middleware.ts width nextauth和nextjs

h6my8fg2  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(127)

`我使用next-auth.js和Credential作为我的登录提供者,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”,``

ep6jt1vc

ep6jt1vc1#

指定回调URL

callbackUrl指定用户登录后重定向到哪个URL。默认为发起登录的页面URL

import { signIn } from "next-auth/react";
//...
signIn("credentials", {
  email,
  password,
  callbackUrl: '/'
}

这将在登录操作后将用户重定向到/ URL。

相关问题