首页 文章

如何处理护照身份验证响应并将其显示给用户

提问于
浏览
0

我正在使用护照本地策略验证我的 nodeJs 应用程序 . 一切都很好 . 但是,如何向用户显示他输入的相应消息 invalid login credentials . 我现在的代码只是在屏幕上发送 401 unauthorized error .

这是我的代码

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

});

1 回答

  • 1

    documentation已在 Custom Callback 部分清楚地描述了您的案例 .

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

    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);
    }
    

    您不需要指定后一个回调 .

相关问题