What does passport.authenticate() return?

Hello, I have one question concerning this few lines of code that I have taken from Passport.js documentation:

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);
  });

So we see here that this last function is being called only if the passport.authenticate() function was successful, so what does it return, is it the next() method “telling” us to go to the next function or is it a boolean value so when it returns true, it goes to the next function in .post method?

Reading the documentation for passport and node-express, I imagine the passport.authenticate('local') function will call next() if successful. If not, I would think authentication will fail and not pass control to the callback function doing the redirect.

If you look further in passports docs it says how to handle success or failure:

passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login',
                                   failureFlash: true })

See also docs: https://expressjs.com/en/4x/api.html#app.METHOD

Hi bartek, passport.authenticate() returns a middleware function. If you to invoke it inside route function and catch any errors you have to do this:

app.get('/', (req, res, next) => {
   passport.authenticate('local', {}, (err, user, info) => { ... })(req, res, next);
})

when passport.authenticate() works then it sets the property user in the request object.

1 Like