How to pass a parameter through my passport.js network?

I use passport.js to authenticate users. I would like to be able to pass in the username collected from the user that will reach the end of the authentication process so that I can save the username when creating the user (if it does not already exist). I tried this:

app.get("/auth/google", function(request, response) { console.log(request.query.username); passport.authenticate("google", { scope: [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ] })(request, response); }); app.get("/auth/google/callback", function(request, response) { console.log(request.query.username); passport.authenticate("google", { successRedirect: "/", failureRedirect: "htm/error" })(request, response); }); 

Calling / auth / google displays the username, but the callback prints undefined. Even if I could get the username for the callback, I'm still not sure how to get it in the google strategy. Should I then create my own strategy to get this to work?

+8
javascript
source share
2 answers

You can pass the state object to the .authenticate passport, for example:

 passport.authenticate("google", { scope: [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ], state: request.query.username })(request, response); 

You can access the state through req.query.state.

The username must be a string, not an object. If you want to keep the object in state, first call JSON.stringify and parse it in the callback.

+7
source share

For those using OpenID, req.query seems to be overwritten with OpenId query parameters and therefore cannot be passed directly. However, you can attach variables to req.session.

 router.get('/auth/social', (req, res, next) => { req.session.foo = req.query.foo; next(); }, passport.authenticate('social')); 

and do not forget to include the passReqToCallback flag in the strategy options:

 { passReqToCallback: true, returnURL: config.app.returnUrl, realm: config.app.realm, apiKey: config.app.apiKey } 
+1
source share

All Articles