Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
Hyra Avatar asked Nov 11 '14 07:11

Hyra


People also ask

Is Passport good for authentication?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.

How does Passport authenticate local work?

The local authentication strategy authenticates users using a username and password. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.

How do I pass additional parameters to passport authenticate?

You can use the request itself to transfer some additional parameters from and to the strategy function. In the following example the two parameters _toParam and _fromParam are used for this concern. app. get('/auth/facebook/:appId', function(req,res,next){ req.


1 Answers

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.

like image 150
magmel Avatar answered Sep 24 '22 07:09

magmel