2014-10-07 89 views
5

根据the documentation,如果我是这样处理身份验证请求,我将能够捕获成功的尝试。如何使用nodejs /护照处理未经授权的请求

app.post('/login', 
    passport.authenticate('local'), 
    function(req, res) { 
    // If this function gets called, authentication was successful. 
    // `req.user` contains the authenticated user. 
    res.redirect('/users/' + req.user.username); 
    }); 

但是,像文件说:

默认情况下,如果验证失败,护照会返回一个401个Unauthorized状态作出反应,和任何其他途径处理程序将不会被调用。如果身份验证成功,则会调用下一个处理程序,并将req.user属性设置为已通过身份验证的用户。

我该如何处理未经授权的登录尝试?

我知道我可以用自定义中间件来处理它,但有没有更好的方法?

回答

10

您应该看看passport docs中的自定义回调部分,其中介绍了如何覆盖处理认证请求的内置行为。您可以编写一个自定义回调函数,用于服务您从策略中调用的done函数的用途。

app.get('/login', function(req, res, next) { 
    /* look at the 2nd parameter to the below call */ 
    passport.authenticate('local', function(err, user, info) { 
    if (err) { return next(err); } 
    if (!user) { return res.redirect('/login'); } 
    req.logIn(user, function(err) { 
     if (err) { return next(err); } 
     return res.redirect('/users/' + user.username); 
    }); 
    })(req, res, next); 
}); 

再看第二个参数为passport.authenticate调用,这将作为您从本地策略调用完成的功能。

查看在下面的代码中调用完成的函数,该函数为您为护照定义的本地策略。您可以根据来自API调用或数据库操作的响应,根据策略设置各种可用参数,如err,user,info来调用done函数。这些参数将通过passport.authenticate调用上述函数定义进行处理。

passport.use(new LocalStrategy(
    function(username, password, done) { 
    /* see done being invoked with different paramters 
     according to different situations */ 
    User.findOne({ username: username }, function (err, user) { 
     if (err) { return done(err); } 
     if (!user) { return done(null, false); } 
     if (!user.verifyPassword(password)) { return done(null, false); } 
     return done(null, user); 
    }); 
    } 
)); 
+1

谢谢,作品很棒 – Joseph 2016-03-26 12:20:42