Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PassportJS - Dynamically set state to allow redirect on callback

So I'm working off the information that was given here to add the ability that Google will redirect to the page a user was at before it redirected to google. I'm currently using the latest versions of Express, PassportJS, and Google oauth2.

For example, if a user hits page http://example.com/privatecontent, it'll automaticially redirect to Google asking to sign in, and after it's sucessful it returns to my Node App, except it doesn't know the last page was /privatecontent and instead redirects to the index.

If I understand right, I can use the state parameter to let Google know to send the state param back so I can read it and redirect myself.

I essentially would like my function to look a little something like this, but I don't have access to req.headers, or just don't know how honestly within passport.authenticate.

app.get("/auth/google", passport.authenticate("google", {
  scope: ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"],
  state: base64url(JSON.stringify({
    lastUrl: req.headers['referer']
  }))
}), function(req, res) {});
like image 622
Dustin Avatar asked Dec 05 '14 03:12

Dustin


1 Answers

Make a custom middleware

function myCustomGoogleAuthenticator(req, res, next){
    passport.authenticate({
        scope: ...
        state: // now you have `req`
    })(req, res, next);
    //^ call the middleware returned by passport.authenticate
}

Add that to your route instead

app.get("/auth/google", myCustomGoogleAuthenticator, function(req, res) {});
like image 170
laggingreflex Avatar answered Oct 29 '22 11:10

laggingreflex