简体   繁体   English

登录失败将我重定向到 /api/auth/error on next-auth

[英]failed login redirects me to /api/auth/error on next-auth

I'm using next-auth v. 4.18.8 in my login page.我在登录页面中使用 next-auth v. 4.18.8。 This is the final project of my Fullstack JS course.这是我的 Fullstack JS 课程的最终项目。 I'm using a newer version than the one used in the course (next-auth v. 3 is used)我使用的版本比课程中使用的版本更新(使用 next-auth v. 3)

When I insert the correct password, everything works as it should (it redirects me to the desired page).当我输入正确的密码时,一切正常(它将我重定向到所需的页面)。

Inserting the wrong password should throw me to /auth/signin?i=1 so I can handle this query.输入错误的密码会使我进入 /auth/signin?i=1 以便我可以处理此查询。 However, it redirects me to http://127.0.0.1:3000/api/auth/error?error=Request%20failed%20with%20status%20code%20401但是,它将我重定向到http://127.0.0.1:3000/api/auth/error?error=Request%20failed%20with%20status%20code%20401

On console, it shows "POST http://localhost:3000/api/auth/callback/credentials? 401 (Unauthorized)"在控制台上,它显示“POST http://localhost:3000/api/auth/callback/credentials?401 (Unauthorized)”

Here's my code:这是我的代码:

Frontend: Login Page前端:登录页面

  const handleFormSubmit = async values => {
    signIn('credentials', {
     email: values.email,
     password: values.password,
     callbackUrl: 'http://127.0.0.1:3000/user/dashboard'
    })
 }

Frontend: [...nextauth].js前端:[...nextauth].js

export const authOptions = {
  providers: [
    CredentialsProvider({
        name: 'credentials',
        async authorize(credentials, req) {
            const res = await axios.post('http://127.0.0.1:3000/api/auth/signin', credentials)

            const user = res.data

            if (user) {
                return user
            } else {
                throw '/auth/signin?i=1'
            }
          }
    })
  ],

  session: {
    jwt: true
  }, 

  jwt: {
    secret: process.env.JWT_TOKEN
  },

  adapter: MongooseAdapter(process.env.MONGODB_URI)
}
export default NextAuth(authOptions)

Backend: signin.js controller后端:signin.js controller

const authSignin = {

    post: async (req, res) => {
        const {
            name,
            email,
            password,
          } = req.body

          await dbConnect()
          
          const user = await UsersModel.findOne({ email })

          if (!user) {
            return res.status(401).json({ success: false, message: "invalid" })
          }

          const passIsCorrect = await compare(password, user.password)

          if (passIsCorrect) {
            return res.status(200).json({
              _id: user._id,
              name: user.name,
              email: user.email
            })
          }
        
          
          return res.status(401).json({ success: false, message: "invalid" })
 
        }
}

export { authSignin }

Finally: Backend: signin.js routes (using Next Connect):最后:后端:signin.js 路由(使用 Next Connect):


import nextConnect from 'next-connect'

import { authSignin } from '../../../src/controllers/auth/signin'
 
const route = nextConnect()

route.post(authSignin.post)

export default route

One thing I noticed is that when inserting a wrong password, when the code reaches this line on controller:我注意到的一件事是,当输入错误的密码时,当代码到达 controller 上的这一行时:

return res.status(401).json({ success: false, message: "invalid" })

It wont continue to execute the [...nextauth].js file after axios.post, therefore not executing the code below, which should give me the 'i' query to handle on frontend (as stated in next-auth documentation):它不会在 axios.post 之后继续执行 [...nextauth].js 文件,因此不会执行下面的代码,这应该给我在前端处理的“i”查询(如 next-auth 文档中所述):

if (user) {
   return user
} else {
   throw '/auth/signin?i=1'
}

The repository is on GitHub存储库位于GitHub

I think if you pass redirect:false here我想如果你在这里传递redirect:false

const handleFormSubmit = async values => {
    signIn('credentials', {
     email: values.email,
     password: values.password,
     callbackUrl: 'http://127.0.0.1:3000/user/dashboard',
     redirect: false,
    })
 }

Looks like when next-auth encounters an error, it automatically redirects.看起来当next-auth遇到错误时,它会自动重定向。 By setting the redirect option it will not automatically redirect so you could handle the error on client side like this通过设置redirect选项,它不会自动重定向,因此您可以像这样在客户端处理错误

  const handleFormSubmit = async values => {
       const signInResult=signIn('credentials', {
         email: values.email,
         password: values.password,
         callbackUrl: 'http://127.0.0.1:3000/user/dashboard',
         redirect: false,
       })
       If (signInResult.error){
           // Handle Error on client side
       }
      
     }

Also you should not make api request in authorize .此外,您不应在authorize中提出 api 请求。 it will delay the process.它会延迟这个过程。 you could run the signin logic inside the authorize您可以在authorize中运行登录逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM