How to use Facebook Graph API after authenticating with Passport.js facebook strategy?

那年仲夏 提交于 2020-01-05 04:22:08

问题


I've authenticated my user with the Facebook strategy and obtained their user info. My application now needs to hit other graph api endpoints on Facebook. I don't see a way to access a tool to send requests to the Facebook graph api. Upon inspecting the Strategy a little further, I see everything is built around the OAuth 2 strategy.

1) How do I use the facebook strategy to call other graph api endpoints?

2) Am I supposed to drill into the passport api somewhere to access a related oauth object somewhere to make this happen?

Or am I thinking about this wrong and I should be getting the user's access token and using another 3rd party library for querying the facebook api?


回答1:


The latter one, you just need the access token and then you can just send a normal request with vanilla or every lib you'd like (I personally like wreck).

That would look like this then:

Wreck.get('https://graph.facebook.com/me?access_token=' + access_token, function(err, res, payload) { });



回答2:


With 'passport-facebook' strategy :

The accessToken is returned along with the profile.

Lets say you have setup the following :

// .: Passport Strategy :.
const Strategy = require('passport-facebook').Strategy;
passport.use(new Strategy({
  clientID:"IDxxxxxxxxxxxxxxxxxxx",
  clientSecret:"SECRETxxxxxxxxxxxxxxxxxxx",
  profileFields: ['id', 'displayName', 'name', 'picture.type(large)', 'emails'],
  callbackURL:"http://localhost:1337/login/facebook/return"
 }, FacebookAccess )
)
function FacebookAccess(accessToken, refreshToken, profile, cb){
  // accessToken  : valid FB.GraphAPI token
  // refreshToken : undefined for Facebook
  profile.token = accessToken
  return cb(null, profile);
}

The token is included to the profile object that is passed along to the passport.serializeUser function that you decide, for example :

passport.serializeUser(function(user, cb){
  var platform_user = {
    fbid:user.id,
    name:user.displayName,
    mail:user.emails[0].value,
    token:user.token,
    avtr:user.photos[0].value
  }
  cb(null, platform_user)
})


来源:https://stackoverflow.com/questions/28405135/how-to-use-facebook-graph-api-after-authenticating-with-passport-js-facebook-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!