如何使用passport-facebook返回json web token(jwt)而不在重定向url中显示它

时间:2015-09-24 20:14:11

标签: mean-stack jwt passport-facebook

我使用passport-facebook登录MEAN堆栈webapp。成功登录后,我想生成一个JSON Web令牌(jwt)并重定向到我的SPA中的页面。 (res.redirect(' /#/ posts /' + doc.generateJWT()); - 请参阅下面的相关代码。)

我的问题是: 如何将JWT发送到重定向页面而不在URL中显示?

代码:

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());                                        
              }
            }
            });
        });
  });

非常感谢提前!

1 个答案:

答案 0 :(得分:14)

如果您不想在网址上显示您的令牌,则必须将响应发送为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);
}));

然后在您的路由器上将令牌返回为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 });
});