Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is passport.authenticate called twice?

Tags:

passport.js

I'm learning passportjs. I'm looking at the passport-google example here https://github.com/jaredhanson/passport-google/blob/master/examples/signon/app.js

It contains the following lines of code

app.get('/auth/google',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
    res.redirect('/');
});

And subsequently, these lines:

app.get('/auth/google/return',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
    res.redirect('/');
});

Can someone help me understand why the duplicate call to passport.authenticate is needed?

like image 583
lastoneisbearfood Avatar asked Nov 10 '22 00:11

lastoneisbearfood


1 Answers

The two calls actually serve distinct functions depending on what type of request is received and at what stage of authentication the flow is at.

The first call passport.authenticate is to initiate the OpenID authentication (which is what passport-google uses under the hood) and the second call (for the return URL) is used by the OpenID Provider to respond to the prior authentication request. The Passport Strategy reads the relevant assertion from the second request and processes it accordingly -- eventually leading to either a redirection to /login if the assertion failed or a redirection to / if the assertion succeeded.

The source code at https://github.com/jaredhanson/passport-openid/blob/master/lib/passport-openid/strategy.js#L164 contains some well-written comments explaining what's happening.

As a final aside, other Passport strategies may behave differently, so not every strategy with a callback necessarily requires the same seemingly "repeated" calls to passport.authenticate(...).

like image 100
davidjb Avatar answered Dec 05 '22 01:12

davidjb