Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...