如何在Node.js中使用Passport身份验证后发送JSON响应

9
我正在尝试这个git示例。当我将其与我的项目集成时,它可以很好地工作,但我想实现的是将json作为响应发送给客户端/请求,而不是successRedirect:'/ profile'和failureRedirect:'/ signup'。是否有可能发送一个json,或者有其他方法可以实现同样的效果?任何帮助将不胜感激。TU
6个回答

8
您可以在Express应用程序中使用Passport的身份验证函数作为路由中间件。
app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    // Then you can send your json as response.
    res.json({message:"Success", username: req.user.username});
  });

默认情况下,如果身份验证失败,Passport将以401未经授权的状态响应,并且不会调用任何其他路由处理程序。 如果身份验证成功,则将调用下一个处理程序,并将req.user属性设置为经过身份验证的用户。


在我看来,这是最干净的解决方案。 - FluffyBeing

7

我在这里修改了我的代码,将json作为响应发送。

// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
    successRedirect : '/successjson', // redirect to the secure profile section
    failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

app.get('/successjson', function(req, res) {
    res.sendfile('public/index.htm');
});

app.get('/failurejson', function(req, res) {
    res.json({ message: 'hello' });
});

4

有官方的自定义回调文档:

app.get('/login', function(req, res, next) {
  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);
});

https://github.com/passport/www.passportjs.org/blob/master/views/docs/authenticate.md


3
创建新路由,例如:/jsonSend,在其中使用res.json,并将successRedirect: '/jsonSend'。这样就可以了。

请检查我下面的答案。 - pitu
如果这是你需要的,并且它对你有效,那就没问题了 ;) - thyforhtian
是的,我只想在身份验证后发送JSON。 - pitu
有没有其他方法可以在同一个POST请求中获取成功/失败的身份验证? - pitu
1
很抱歉,我不明白你的意思。可以举个例子吗? - thyforhtian
显示剩余2条评论

1
使用护照作为中间件。
router.get('/auth/callback', passport.authenticate('facebook'), 
    function(req, res){
        if (req.user) { res.send(req.user); }
        else { res.send(401); }
    });

-3
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
    successRedirect : '/successjson', // redirect to the secure profile section
    failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

app.get('/successjson', function(req, res) {
    res.sendfile('public/index.htm');
});

app.get('/failurejson', function(req, res) {
    res.json({ message: 'hello' });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接