【问题标题】:passportjs - how to access status message in case of 401passportjs - 如何在 401 的情况下访问状态消息
【发布时间】:2015-07-12 12:24:46
【问题描述】:

我用的是passportjs的本地策略:

passport.use(new LocalStrategy(
function(username, password, done) {
    if (username === "myuser" && password === "mypass")
        return done(null, { name: "myuser" });

    return done(null, false, { data: 'Incorrect username and/or password' });
}));

对于 401 状态,我希望客户端收到我的状态消息:“用户名和/或密码不正确”。相反,我在响应正文中看到的只是“未经授权”一词。如何访问消息?

谢谢。

【问题讨论】:

    标签: node.js passport.js


    【解决方案1】:

    您可以使用 req.authInfo 访问您作为第三个参数传递的对象。然后你可以从中检索data

    【讨论】:

      【解决方案2】:

      问题是这样的:当我接受 POST 请求时:

      app.post('/login', passport.authenticate('local'), function(req, res) {
          console.log(req.authInfo);
          res.send(req.user);
      });
      

      console.log(req.authInfo) 在 401 状态下不会被调用,只有在 200 状态下才会被调用。我该如何解决?

      【讨论】:

        【解决方案3】:

        查看本帖回复:passport.js - Access fail message after 401 error

        您必须将您的 passport.authenticate 放入函数响应中:

        app.post('/login', function(req, res, next) {
            passport.authenticate('local', function(err, user, response) { 
               if(!response.success) {
                  res.status(401).json({ 
                    message: 'Incorrect username and/or password'
                  });
               }
            })(req, res, next);
        });
        

        显然,您还必须将本地策略的第三个参数放入

        if(InvalidPassword or user not exist) {
          return next(null, false, { success: false });
        }
        

        【讨论】:

          猜你喜欢
          • 2022-01-24
          • 2018-01-13
          • 2020-11-23
          • 1970-01-01
          • 2013-08-06
          • 1970-01-01
          • 2022-12-30
          • 2021-02-26
          • 1970-01-01
          相关资源
          最近更新 更多