【问题标题】:Authenticated request to passport local pending本地护照的已验证请求待处理
【发布时间】:2020-01-29 09:51:26
【问题描述】:

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

护照本地配置

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

浏览器检查

【问题讨论】:

  • 任何控制台错误?对于 FE 和 BE。也许是一些 CORS 标头问题?
  • 未发现错误。在我的情况下,来自客户端的请求已成功发送到服务器,但服务器没有处理任何内容。所以我认为问题不来自CORS。用户提交登录按钮后,状态为pending,1、2分钟后变为failed。

标签: reactjs mongodb express authentication passport-local


【解决方案1】:

我已经解决了这个问题。基本上我们只是在 passport.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)
})

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

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

【讨论】:

    【解决方案2】:

    问题是您没有使用正确的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) => {
      ...
    }}
    

    【讨论】:

    • 也可以在这里查看:passportjs.org/docs/authenticate
    • 请参阅 Passport passportjs.org/docs/username-password 的文档,我认为我的配置正确。因为默认情况下 Passport 有两个参数“用户名”和“密码”。如果您看到我从上面的服务器端记录的请求数据,它也有两个字段用户名和密码。我和你有同样的想法,错误可能来自我护照的配置,但一切似乎都很好。
    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 2019-05-08
    • 2014-03-17
    • 1970-01-01
    • 2017-04-02
    • 2016-10-29
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多