Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

node.js - Can you authenticate with Passport without redirecting?

I have the following working code to authenticate through the passport-local strategy:

  app.post('/api/login', passport.authenticate('local-login', {
    successRedirect : '/api/login/success',
    failureRedirect : '/api/login/error',
    failureFlash : true
  }));
  app.get('/api/login/error', function(req, res) {
    res.send(401, {error: req.flash('loginMessage')});
  });
  app.get('/api/login/success', function(req, res) {
    res.send(200, {user: req.user});
  });

However, ideally I want to handle the errors and success messages from one express route, and not redirect to two extra routes.

Is this possible? I tried using a 'custom callback' but that seemed to error out on serializing users for some reason.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use custom callback, such as:

passport.authenticate('local', function (err, account) {
    req.logIn(account, function() {
        res.status(err ? 500 : 200).send(err ? err : account);
    });
})(this.req, this.res, this.next);

In err object you can find all needed errors, which was appeared at authentication.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...