The passport.authenticate() function is a middleware generator used to trigger authentication via a specific strategy or a chain of strategies.
Default Behavior
If no callback is provided, Passport handles the authentication flow automatically:
- Success: The user is logged in,
req.user is populated, and a session is established (if session: true). Depending on options, the user may be redirected. - Failure: An unauthorized response (typically 401) is sent, or the user is redirected to the
failureRedirect URL.
Using a Custom Callback
If you provide a callback, you take responsibility for logging the user in, establishing a session, and handling redirects. The callback signature is:
function(err, user, info, status)
err: An error object if an internal error occurred.user: The authenticated user object on success, or false on failure.info: Additional details provided by the strategy (e.g., profile info or a challenge message).status: An optional HTTP status code (e.g., for remote authentication failures).
Strategy Chaining
You can pass an array of strategy names to authenticate(). Passport will attempt them in order. The first strategy to succeed, redirect, or error will halt the chain. This is useful for API endpoints supporting multiple authentication schemes (e.g., Basic, Digest, and Token).
// Example 1: Default behavior with redirects
passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' });
// Example 2: API usage with session disabled
passport.authenticate('basic', { session: false });
// Example 3: Using a custom callback for manual control
app.get('/protected', function(req, res, next) {
passport.authenticate('local', function(err, user, info, status) {
if (err) { return next(err); }
if (!user) { return res.redirect('/signin'); }
res.redirect('/account');
})(req, res, next);
});