Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return json web token (jwt) with passport-facebook without showing it in the redirect url

I am using passport-facebook to login in a MEAN stack webapp. After successful login, I want to generate a JSON Web Token (jwt) and redirect to a page in my SPA. (res.redirect('/#/posts/'+ doc.generateJWT()); -- please see the associated code below).

My question is: How do I send the JWT to the redirect page without showing it in the URL?

Code:

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


passport.use(new FacebookStrategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: FACEBOOK_CALLBACKURL
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {  
      User.findOne({'fbid':profile.id},function(err, docs) {                  
              if (err){
                //console.log('Error in SignUp: '+err);
                return res.status(401).json(info);
              }                  
              else {
                  if (docs) {
                        //console.log('User already exists');
                        globalid = profile.id;
                        return done(null,docs);
                  } else {
                        // if there is no user with that fbid
                        // create the user
                        var newUser = new User();
                        // set the user's local credentials
                        newUser.fbid = profile.id;
                        globalid = profile.id;

                        newUser.firstname = profile.name.givenName;
                        newUser.lastname = profile.name.familyName;
                        newUser.gender = profile.gender;
                        if(profile.emails){
                        newUser.fbemail = profile.emails[0].value;
                        };
                        newUser.fblink = profile.profileUrl;
                        newUser.fbverified = profile.verified;

                        // save the user
                        newUser.save(function(err) {
                          if (err){
                            //console.log('Error in Saving user: '+err); 
                            return res.status(401).json(info); 
                          }
                          //console.log('User Registration succesful'); 
                          return done(null, newUser);
                        });
                   } 
                 }
              });
    });
}));

var router = express.Router();

router.get('/auth/facebook', 
  passport.authenticate('facebook', { scope : 'email' }
));

router.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { session: false, failureRedirect: '/'}),  
  function(req, res,done) {
    var redirection = true;
    User.findOne({ 'fbid': globalid }, function (err, doc){
            //console.log("Generating token");
            doc.token = doc.generateJWT();
            doc.save(function(err) {
              if (err){
                //console.log('Error in Saving token for old user: '+err); 
                return res.status(401).json(info); 
              }
             else
             { 
              //console.log('User Login succesful');
              redirection = doc.mobileverified;
              //console.log(redirection);
              //return done(null, doc);
              if(doc.mobileverified === true){
                    console.log("Token:",doc.generateJWT());                       
                    res.redirect('/#/posts/'+ doc.generateJWT());
              }
              else{

                  console.log("Token:",doc.generateJWT());
                  //res.json({token: doc.generateJWT()});
                  res.redirect('/#/register/' + doc.generateJWT());                                        
              }
            }
            });
        });
  });

Many Thanks in advance!

like image 298
user5034543 Avatar asked Sep 24 '15 20:09

user5034543


1 Answers

If you don't wanna show your token on the url you have to send the response as json

var fbOptions = {
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: FACEBOOK_CALLBACKURL
};
passport.use(new FacebookStrategy(fbOptions, function(token, refreshToken, profile, done) {
    var user = profile;
    // NOTE: ‘my_token’ we will use later 
    user.my_token = 'generate your jwt token';
    done(null, user);
}));

And then on your router return the token as json

app.get('/auth/facebook/callback', passport.authenticate('facebook', {session: false, failureRedirect : '/'}), function(req, res) {
 // The token we have created on FacebookStrategy above 
 var token = req.user.my_token;
 res.json({ token: token });
});
like image 121
diegoddox Avatar answered Oct 04 '22 03:10

diegoddox