【问题标题】:How to handle passport authentication response and show it to the user如何处理护照认证响应并将其显示给用户
【发布时间】:2015-01-07 10:12:02
【问题描述】:

我正在使用护照本地策略验证我的 nodeJs 应用程序。一切正常。但是我怎样才能向用户显示他输入了无效的登录凭据的适当消息。我目前的代码只是在屏幕上发送401未授权错误

这是我的代码

passport.use(new LocalStrategy(function(username, password, callback) {
    User.findOne({
        username : username
    }, function(err, user) {
        if (err) {
            return callback(err);
        }

        // No user found with that username
        if (!user) {
            return callback(null, false);
        }

        // Make sure the password is correct
        user.verifyPassword(password, function(err, isMatch) {
            if (err) {
                return callback(err);
            }

            // Password did not match
            if (!isMatch) {
                return callback(null, false);
            }

            // Success
            return callback(null, user);
        });
    });
}));

exports.isLocalAuthenticated = passport.authenticate('local', {
    session : true
});

router.post('/', authController.isLocalAuthenticated, function(req, res) {
    //here I want to show the error message to user

});

【问题讨论】:

    标签: node.js express passport.js


    【解决方案1】:

    documentation自定义回调部分清楚地描述了您的情况。

    您需要像这样添加自定义回调:

    exports.isLocalAuthenticated = function(req, res, next) {
        passport.authenticate('local', function(err, user, info) {
            if (err) { return next(err); } //error exception
    
            // user will be set to false, if not authenticated
            if (!user) {
                res.status(401).json(info); //info contains the error message
            } else {
                // if user authenticated maintain the session
                req.logIn(user, function() {
                    // do whatever here on successful login
                })
            }    
        })(req, res, next);
    }
    

    后面的回调不需要指定。

    【讨论】:

    • req,res 在这里未定义!根据文档,唯一的方法是我们需要在路由本身中调用此身份验证函数。
    • @ShivaMothkuri 已更新。
    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 2021-03-27
    相关资源
    最近更新 更多