身份验证请求到本地护照待处理

时间:2020-01-29 09:51:26

标签: reactjs mongodb express authentication passport-local

我正在使用Node,MongDB,Passport,Express和React开发一个身份验证应用程序。我正在尝试修复此问题2天,但仍然会卡住。错误是在数据发送到服务器后,服务器未处理该请求。这是我的配置:

Passport Local配置

  const LocalStrategy = require('passport-local').Strategy
  passport.use({
    usernameField: 'username',
    passwordField: 'password'
  }, new LocalStrategy((username, password, done) => {
    /*Match username or not*/
    User.findOne({ email: username }, (err, user) => {
      if (err) {
        console.log(`Error: ${err}`)
        return done(err)
      }
      /* user not found */
      if (!user) {
        console.log(`User not matched!`)
        return done(null, false, {
          message: 'That email is not registered'
        })
      }
      /*Match password*/
      bcrypt.compare(password, user.password, (err, isMatch) => {
        if (err) throw err
        if (isMatch) {
          return done(null, user)
        } else {
          return done(null, false, {
            message: 'Password incorrect'
          })
        }
      })
    })
  }))

身份验证路由器

router.post('/auth/local/login', (req, res, next) => {
  console.log(`Login info: ${JSON.stringify(req.body)}`)
  passport.authenticate('local', {
    successRedirect: "/dashboard",
    failureRedirect: "/login",
    failureFlash: false
  })
})

客户端

  formData.append('username', username)
  formData.append('password', password)
  const data = new URLSearchParams(formData)
  fetch('/auth/local/login', {
    method: 'POST',
    body: data
  })
    .then(res => res.json())
    .then(json => {
      console.log(`${JSON.stringify(json)}`)
      handleAuthenticated(json)
    })
    .catch(err => console.log(err))

在服务器端登录

Server started successfully at 3001!
Database connected successfully!
Login info: {"username":"newemail@yahoo.com","password":"123456"}

通过浏览器检查

enter image description here

2 个答案:

答案 0 :(得分:1)

我已解决此问题。基本上,我们只在password.authenticate('local')的回调函数中处理身份验证,如下所示:

router.post('/auth/local/login', (req, res, next) => {
   passport.authenticate('local', {
     session: false
    }, (err, user, info) => {
      if(err || !user) return res.status(401).json({
         auth: false,
         msg: "Authentication failed",
         token: null
      }) 
      req.login(user, {session: false}, err => {
         if(err) res.send(err)
      })
      const token = jwt.sign(user.id, key.tokenSecret)
      return res.status(200).json({
        auth: true,
        msg: "Login successfully",
        token: token
      })
   })(req, res)
})

**会话设置为false,因为我们不想在会话中存储用户。

现在它可以完美运行了。在客户端,根据从服务器收到的响应,将用户重定向到正确的页面。我已经测试过:成功和失败

enter image description here

答案 1 :(得分:0)

问题是您没有使用正确的方法签名passport.use。正确的是这个:

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'passwd'
  },
  function(username, password, done) {
    // ...
  }

不是这个:

passport.use({
    usernameField: 'username',
    passwordField: 'password'
  }, new LocalStrategy((username, password, done) => {
  ...
}}