📜 ⬆️ ⬇️

The subtleties of working with PassportJs

Recently working on another project that uses passporjs , I came across several problems that other developers have encountered on the Internet. But I did not find any answers on the Internet (maybe I looked badly).

I will tell about these problems and how I solved them.

The documentation on PassportJS and its 3-d Strategy seems to be enough to get started, but during the development I had such problems:
1. facebook did not provide the fields that I need, for example, email
2. vkontakte, also did not provide email, but for a different reason, rather than facebook

And so, we solve the first problem.
The documentation states that scope, must be passed to options, when performing the actual authorization:
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login', scope: [ 'email', 'publish_actions', 'user_friends', 'user_about_me', 'user_birthday' ] }), function(req, res) { // Successful authentication, redirect home. res.redirect('/'); }); 

')
But, email did not return anyway. As a result, after sourceing, it became clear that the scope should be passed in the settings of the Strategy itself, separated by a comma:
 passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: "http://localhost:3000/auth/facebook/callback", scope: 'email', enableProof: false }, function(accessToken, refreshToken, profile, done) { User.findOrCreate({ facebookId: profile.id }, function (err, user) { return done(err, user); }); } )); 


Actually it worked.

2. But, the problem with the use of passport-vkontakte , did not dare, because VKontakte is special and gives the email not in the user profile, but immediately when access_token is requested. Began to pick the source more deeply. As a result, I found such a piece of code in passport-oauth2 :
 if (arity == 5) { self._verify(accessToken, refreshToken, params, profile, verified); } else { // arity == 4 self._verify(accessToken, refreshToken, profile, verified); } 

Actually, this suggests that you can send a verification callback with 5 parameters and a raw reply to VKontakte will come to params when receiving accessToken:
 passport.use(new VKontakteStrategy({ clientID: VKONTAKTE_APP_ID, // VK.com docs call it 'API ID' clientSecret: VKONTAKTE_APP_SECRET, callbackURL: "http://localhost:3000/auth/vkontakte/callback" }, function(accessToken, refreshToken, params, profile, done) { //params.email -   ! } )); 


All for now.

Source: https://habr.com/ru/post/262979/


All Articles