GithubHelp home page GithubHelp logo

jaredhanson / passport-facebook Goto Github PK

View Code? Open in Web Editor NEW
1.3K 44.0 446.0 169 KB

Facebook authentication strategy for Passport and Node.js.

Home Page: https://www.passportjs.org/packages/passport-facebook/?utm_source=github&utm_medium=referral&utm_campaign=passport-facebook&utm_content=about

License: MIT License

Makefile 0.34% JavaScript 99.66%
passport facebook oauth2

passport-facebook's Introduction

passport-facebook

Passport strategy for authenticating with Facebook using OAuth 2.0.

This module lets you authenticate using Facebook in your Node.js applications. By plugging into Passport, Facebook Login can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

๐ŸŒฑ Tutorial โ€ข :brain: Understanding OAuth 2.0 โ€ข :heart: Sponsors

Developed by Jared Hanson.

Advertisement
The Complete Node.js Developer Course
Learn Node. js by building real-world applications with Node, Express, MongoDB, Jest, and more!

Install

$ npm install passport-facebook

Usage

Register Application

The Facebook strategy authenticates users using their Facebook account. Before your application can make use of Facebook's authentication system, you must first register your app. Once registered, an app ID and secret will be issued which are used by Facebook to identify your app. You will also need to configure a redirect URI which matches the route in your application.

Configure Strategy

Once you've registered your application, the strategy needs to be configured with your application's app ID and secret, along with its OAuth 2.0 redirect endpoint.

The strategy takes a verify function as an argument, which accepts accessToken, refreshToken, and profile as arguments. accessToken and refreshToken are used for API access, and are not needed for authentication. profile contains the user's profile information stored in their Facebook account. When authenticating a user, this strategy uses the OAuth 2.0 protocol to obtain this information via a sequence of redirects and API requests to Facebook.

The verify function is responsible for determining the user to which the Facebook account belongs. In cases where the account is logging in for the first time, a new user record is typically created automatically. On subsequent logins, the existing user record will be found via its relation to the Facebook account.

Because the verify function is supplied by the application, the app is free to use any database of its choosing. The example below illustrates usage of a SQL database.

var FacebookStrategy = require('passport-facebook');

passport.use(new FacebookStrategy({
    clientID: process.env['FACEBOOK_APP_ID'],
    clientSecret: process.env['FACEBOOK_APP_SECRET'],
    callbackURL: 'https://www.example.com/oauth2/redirect/facebook',
    state: true
  },
  function verify(accessToken, refreshToken, profile, cb) {
    db.get('SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?', [
      'https://www.facebook.com',
      profile.id
    ], function(err, cred) {
      if (err) { return cb(err); }
      
      if (!cred) {
        // The account at Facebook has not logged in to this app before.  Create
        // a new user record and associate it with the Facebook account.
        db.run('INSERT INTO users (name) VALUES (?)', [
          profile.displayName
        ], function(err) {
          if (err) { return cb(err); }
          
          var id = this.lastID;
          db.run('INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)', [
            id,
            'https://www.facebook.com',
            profile.id
          ], function(err) {
            if (err) { return cb(err); }
            
            var user = {
              id: id,
              name: profile.displayName
            };
            return cb(null, user);
          });
        });
      } else {
        // The account at Facebook has previously logged in to the app.  Get the
        // user record associated with the Facebook account and log the user in.
        db.get('SELECT * FROM users WHERE id = ?', [ cred.user_id ], function(err, user) {
          if (err) { return cb(err); }
          if (!user) { return cb(null, false); }
          return cb(null, user);
        });
      }
    });
  }
));

Define Routes

Two routes are needed in order to allow users to log in with their Facebook account. The first route redirects the user to the Facebook, where they will authenticate:

app.get('/login/facebook', passport.authenticate('facebook'));

The second route processes the authentication response and logs the user in, after Facebook redirects the user back to the app:

app.get('/oauth2/redirect/facebook',
  passport.authenticate('facebook', { failureRedirect: '/login', failureMessage: true }),
  function(req, res) {
    res.redirect('/');
  });

Examples

  • todos-express-facebook

    Illustrates how to use the Facebook strategy within an Express application. For developers new to Passport and getting started, a tutorial is available.

  • todos-express-facebook-popup

    Illustrates how to use progressive enhancement to display the the Facebook login dialog in a popup window. State is kept during the OAuth 2.0 flow and used to close the window for requests using that display mode.

FAQ

How do I ask a user for additional permissions?

If you need additional permissions from the user, the permissions can be requested via the scope option to passport.authenticate().

app.get('/auth/facebook',
  passport.authenticate('facebook', { scope: ['user_friends', 'manage_pages'] }));

Refer to permissions with Facebook Login for further details.

How do I re-ask for for declined permissions?

Set the authType option to reauthenticate when authenticating.

app.get('/auth/facebook',
  passport.authenticate('facebook', { authType: 'reauthenticate', scope: ['user_friends', 'manage_pages'] }));

Refer to re-asking for declined permissions for further details.

How do I obtain a user profile with specific fields?

The Facebook profile contains a lot of information about a user. By default, not all the fields in a profile are returned. The fields needed by an application can be indicated by setting the profileFields option.

new FacebookStrategy({
  clientID: FACEBOOK_APP_ID,
  clientSecret: FACEBOOK_APP_SECRET,
  callbackURL: "http://localhost:3000/auth/facebook/callback",
  profileFields: ['id', 'displayName', 'photos', 'email']
}), ...)

Refer to the User section of the Graph API Reference for the complete set of available fields.

How do I include app secret proof in API requests?

Set the enableProof option when creating the strategy.

new FacebookStrategy({
  clientID: FACEBOOK_APP_ID,
  clientSecret: FACEBOOK_APP_SECRET,
  callbackURL: "http://localhost:3000/auth/facebook/callback",
  enableProof: true
}, ...)

As detailed in securing graph API requests, requiring the app secret for server API requests helps prevent use of tokens stolen by malicous software or man in the middle attacks.

Why is #_=_ appended to the redirect URI?

This behavior is "by design" according to Facebook's response to a bug filed regarding this issue.

Fragment identifiers are not supplied in requests made to a server, and as such this strategy is not aware that this behavior is exhibited and is not affected by it. If desired, this fragment can be removed on the client side. Refer to this discussion on Stack Overflow for recommendations on how to accomplish such removal.

Authors

License

The MIT License

Copyright (c) 2011-2023 Jared Hanson

passport-facebook's People

Contributors

aymanosman avatar bachp avatar dan-silver avatar duereg avatar emmanuelgautier avatar ferlores avatar fmalk avatar fonger avatar gimenete avatar jaredhanson avatar lesterzone avatar naartjie avatar niftylettuce avatar ollynov avatar pdehaan avatar robertdimarco avatar rwoody avatar staxmanade avatar stevebest avatar suryagh avatar weichienhsu avatar woloski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

passport-facebook's Issues

redirect to OAuth Dialog problems

This did previously work for me, now doing some test it seems to have stopped working.
Users already authenticated still work okay.

When passport does the redirect back to the dialog i get the following error:

"Refused to display document because display forbidden by X-Frame-Options."

My investigations have lead me to:

https://developers.facebook.com/docs/authentication/canvas/

and specifically:

"Because your application is being loaded in an iframe, returning a 302 to redirect the user to the OAuth Dialog will be unsuccessful. Instead you must redirect by setting the Javascript window.top.location property, which causes the parent window to redirect to the OAuth Dialog URL"

I'm a little confused at this point, is this something passport-facebook should be doing, I should be doing or is there some other issue here?

Can't Authenticate

Hi,
I'm trying to authenticate my session using express and passport-facebook, using redis as session store. In localhost everything is going well, but when I run from my Cloud Server(Rackspace), I always get "#=" in return method and "req.isAuthenticate()" is false.

I'm using HAProxy to redirect to my node instance.

Thank you!
ps: Sorry about my english!

Could not run the Passport-Facebook example

I tried replacing the appid and secret and ran it ... but when I click on login with facebook it takes me to facebook with error
after logging into Facebook it does not redirect

I also saw some URL encoding happening ... I am not sure if this needs to get turned off ...

https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Ffacebook%2Fcallback&client_id=40319531303xxxx&type=web_server

Is there any special configuration that needs to be done Facebook app ? or am i missing something ...

we are seriously considering using Passport-Facebook in our company... although we need to see how to fit passport because
we have authentication happening through Facebook-IOS SDK on the IOS device and all that is sent to the server is the
facebook token... are there any examples demonstrating this usecase....

Is there a way for FacebookStrategy to pick up clientid and secret dynamically?

I want to set the two below values dynamically:

clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,

I tried something like below:

app.get('/auth/facebook',
passport.authenticate('facebook', { clientID:"xxx", clientSecret:"yyy"}));

On running the application, when I sign in with facebook, I see that the values set above are present in options, and are getting displayed.

FacebookStrategy.prototype.authorizationParams = function (options) {
console.log("options: "+JSON.stringify(options));
var params = {},
display = options.display,
auth_type = options.auth_type;
clientID = options.clientID;
clientSecret = options.clientSecret;
if (display) params['display'] = display;
if (auth_type) params['auth_type'] = auth_type;
if (clientID) params['clientID'] = clientID;
if (clientSecret) params['clientSecret'] = clientSecret;
console.log("params: "+JSON.stringify(params));
return params;
}

Now I want to be able to set these values passed dynamically to FACEBOOK_APP_ID and FACEBOOK_APP_SECRET. Please guide me how that can be done.

Thank you.

getAccessToken

is there anyway to get the access token? If it's the first time i'm getting granted permission to the page, i manage to get the accesstoken through the callback, but if i get back to the page, there is no way i can get that token back.

Is there any options like passport.getAccessToken()? or something similar?

what would be the best way to do it?!

thanks

Semi-Dynamic callbackUrl

Currently it does not seem possible to use a 'semi-dynamic' callbackUrl. In the examples, one specifies a static callbackUrl = 'http://localhost/auth/facebook/callback', which isn't very useful for when you want to remember where authentication has taken place.

For instance, if the user clicks on a Login link on /page/1/2/3 then he/she would expect to be returned to the /page/1/2/3 upon authentication. When creating the params for the callbackUrl, passport should check for an optional passed GET parameter called 'next' and encode it into the callbackUrl. The 'semi-dynamic' callbackUrl would then be 'http://localhost/auth/facebook/callback?next=/page/1/2/3'

The logic in /auth/facebook/callback would then be able to get the next parameter and perform the appropriate action to take the user back to /page/1/2/3

Pass display=popup to Facebook Authentication

Hi,

Facebook shows a different allow dialog based on a GET parameter: display=popup. I dug through the code and couldn't find a gentle place to add it. There are no options for passing more GET parameters to the authorization dialog, and even the oAuth package doesn't seem to accept and stringify more parameters.

A very hacky solution I found was to set the authorizationURL option with the display=popup and add another fake parameter. It's really bad and ugly but it works:

authorizationURL: "https://www.facebook.com/dialog/oauth?display=popup&pip"

Looking for ideas on how we can change passport-facebook to add this get parameters without writing those hacks.

Scope Permissions

am i missing something? or doing something wrong? because scope doesn't seem to work

i do the following:

app.get('/auth/facebook',
        passport.authenticate('facebook'), {
            scope: ['user_about_me', 'user_photos', 'email', 'publish_stream']
        }
);

but all i ever get is "THIS APP WILL RECEIVE: Your basic info"
i tried setting permissions in my facebook app permission page as well and preview looks good there but when i connect with passport-facebook still only get "Your basic info"

auth multiple Facebook apps

I would like to be able to auth multiple Facebook apps in a single express app.
The main issue for me I think is that each Facebook app has different clientId and clientSecret.

Would it be possible to have multiple instances of passport-facebook within the same app, using different urls?

path problem

if I use the following URL's everything works fine (great code by the way, many thanks).

/facebook
/facebook/callback

but if i change it to the following

/facebook/appname
/facebook/callback

I'm not sure what state my app is in but it doesn't work, I'm guessing the callback url is somehow dependent on the auth url?

Can't request profile fields that don't exist in Portable Contacts

Currently it doesn't seem that you can request profile fields that don't exist in the Portable Contacts map that we have. This can lead to some odd cases where by requesting additional fields not normally passed back by /me, you lose access to other fields.

One example is with birthdays & photos.

The "picture" field is not normally returned by the Facebook API in /me unless specifically requested in the fields parameter. This is handled by passport by passing in "photos" as a profile field in the strategy.

Birthday is not in our list of Portable Contacts <-> Facebook contact mappings, but we normally get access to it simply by adding the "user_birthday" permission to the auth scope, which causes it to be returned in the default fields in "/me."

However, since the "brithday" field doesn't exist in portable contacts, attempting to pass in "birthday" to the strategy's profileFields results in it not actually being returned, since it results in a /me call with only the mappable fields requested.

Express 3.3.4 not compatible for middleware chaining

The piece of code taken from passport-facebook github page,

app.get('/auth/facebook',
passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});

when this chaining is done, the successful auth block isnt invoked at all. but the accesstoken is received by passport, so the error is: say '/auth/facebook/callback' is not serving response and timesout.

one more hint: when the accesstoken is received the done(null,profile) in above case says, "express middleware initialize failed". still investigating on this.

FB connect Unauthorized source IP address

Hi,
I am getting the below error. FB connect in local is working fine but in server the error occurs.

500 failed to fetch user profile (status: 400 data: {"error":{"message":"(#5) Unauthorized source IP address","type":"OAuthException","code":5}})

scope option issue

Hi Jared.

Scope option is not working since yesterday. I'm getting an error when i try to get oauth token. So i have to remove scope option. But this time i cannot demand for extended permissions from user.

passport.authenticate("facebook", { scope: ["user_about_me", ...

Get extra FanPages AccessTokens

Hi! Thanks for your multiple strategies ๐Ÿ‘

My question is how to get the extra access tokens to manage the user fan pages when they accept this scope:
passport.authenticate('facebook',{ scope: ['manage_pages','read_stream', 'publish_actions'] })

I supose I might make the extra calls, but I don't receive the fanpages IDs to.
Thank you for your time

Unclear Functionality - Documentation Request

I am failing to understand the authorization process, and I have many questions about how this is supposed to work that are probably no-brainers for some people:

After configuring the /login route and the /login/callback route, will all further requests with in my programs always be authenticated? For example, if I call req.isAuthenticated() in the callback for the /login/callback route, I will get TRUE, but if I call req.isAuthetnticated() in arbitrary routes later on, I am not getting TRUE. How do I ensure authentication across routes that are not callbacks?

The access tokens and refresh tokens - how do you get access to them on a per-request basis? Currently, they are parameters only of the /login/callback route. What if I want to have a multitude of RESTful API endpoints all of which need authorization?

Configuring passport.use(function(){ //... }) seems to be simply setting the function that passport.authorize will later reference. What if I don't want to specify a path like /login/callback, but I want to be able to have a different callbackURL each time I authorize (for example, every action the user takes, I want verify they are still authorized, but I don't ALWAYS want to take them back to the initial /login/callback page - I may want to take them to /user/:user_id/project/:project_id).

recover POST body in callback function

Hi,
is it correct that the 'passReqToCallback' option of the OAuth2Strategy` constructor returns the current request object to verify callback?

In case of a 2-way authentication like FB oauth, this would mean that the initial request object is not available anymore in the callback. https://github.com/jaredhanson/passport-oauth/blob/master/lib/passport-oauth/strategies/oauth2.js#L136-L142

Also, see my question on SO: http://stackoverflow.com/questions/17951460/passportjs-facebook-pass-request-to-callback (for wich I'm tumbleweeded :))

accessing the token

I need access to the users accessToken to make calls to access the facebook graph API.

Once a user has authenticated with Facebook is there a defined way to get the accessToken, or should I save this to either the user doc in the DB or the users session (are there any security issues doing this)?

Thanks

passport-facebook and CORS

Has anyone tried to implement passport-facebook with CORS?

My webapp and authentication server are running on different domains and I can't find a way to implement passport-facebook.

PS. Local strategy works fine.

Overriding the Strategy userProfile from the application level...

I dont want to be dependent on the node_modules, as I have a script that "builds" the application, and pulls in the node_modules. The facebook strategy works fine, but I need to re-write it from my application, so I am sure the answer is a facepalm .... Im using Passport for Facebook - in the Strategy there is a function FacebookStrategy.prototype.userProfile = function().... and I include it in my app like so: FacebookStrategy = require('passport-facebook').Strategy; but I need to change that function, so I do after the require... FacebookStrategy.userProfile = function()... but it doesnt seem to override it. thoughts...

500 error

Hi there,
after a successful redirect to the facebook page and a successful login to facebook, I get this error in express

500
function verified(err, user, info) { if (err) { return self.error(err); } if (!user) { return self.fail(info); } self.success(user, info); }

any ideas what needs to be done?
Thanks

Cant get display popup to work

Hey guys, im trying to open the auth screen in a popup. But it aint working out, the parameters that i'm using are:

passport.authenticate('facebook', {display: 'popup' , scope: [ 'email'] })

But it keeps opening it in the current window. Am i missing something ? Thanks !

Function " function(accessToken, refreshToken, profile, done) { " not invoked

The statement "console.log('i actually came here!');" does not execute, which according to the given example should. Everything else works fine. I am unable to save data upon authentication from facebook by user.

var FacebookStrategy = require('passport-facebook').Strategy; 
var FACEBOOK_APP_ID = '148113458721431';
var FACEBOOK_APP_SECRET = 'f6f82a0d976265d1838112dd780af03c';

    passport.use(new FacebookStrategy({
                                clientID: FACEBOOK_APP_ID,
                                clientSecret: FACEBOOK_APP_SECRET,
                                callbackURL: "/home"
                                },

                                function(accessToken, refreshToken, profile, done) {                                    


                process.nextTick(function () {

                console.log('i actually came here!');

                // To keep the example simple, the user's Facebook profile is returned to
                // represent the logged-in user.  In a typical application, you would want
                // to associate the Facebook account with a user record in your database,
                // and return that user instead.
                return done(null, profile);
                });


                            }
                    )
        );

Error: no strategy registered under name: facebook

OpenIDStrategy = require('passport-openid').Strategy
FacebookStrategy = require('passport-facebook').Strategy
User = require('../models/user')

passport.use new OpenIDStrategy(
  returnURL: "http://localhost:5000/auth/openid/return"
  realm: "http://localhost:5000/"
  profile: true
, (identifier, profile, done) ->
  User.findOne
  open_identifier: identifier
, (err, user) ->
  unless user
    User.findOne {email_id: profile.emails[0].value}, (err, user) ->
      if user
        new_user = user
      else
        new_user = new User({first_name: profile.givenName, open_identifier: identifier,       last_name: profile.familyName, email_id: profile.emails[0].value, password: 'temptemp0101'})
        new_user.save()
      done(null, new_user)
  else
    done(null, user)

)

passport.use new FacebookStrategy(
clientID: '3818lalala1928213'
clientSecret: '2858bacd542a61a4325lalalac8'
callbackURL: "http://localhost:5000/auth/facebook/callback"
), (accessToken, refreshToken, profile, done) ->
console.log "yay"
console.log profile
done(null, 'a')

Now when i do a console.log passport, this is what i get

{ _key: 'passport',
  _strategies: 
{ session: { name: 'session' },
 openid: 
{ name: 'openid',
     _verify: [Function],
     _profile: true,
     _pape: undefined,
     _passReqToCallback: undefined,
     _relyingParty: [Object],
     _providerURL: undefined,
     _identifierField: 'openid_identifier' },
  '[object Object]': [Function] },

_serializers: [ [Function] ],
_deserializers: [ [Function] ],
_infoTransformers: [],
_framework: null,
userProperty: 'user',
version: '0.1.17',
Passport: [Function: Passport],
Strategy: [Function: Strategy],
strategies: { SessionStrategy: { [Function: SessionStrategy] super
: [Function: Strategy] } } }

As you will notice there is no 'facebook' strategy in the list of strategies. Any idea what could be wrong?

Add more info on parsing error

Currently the code looks like this

 } catch (ex) {
      done(new Error('Failed to parse user profile'));
    }

So the original error is lost and instead we get an error without any details:

Error: Failed to parse user profile
    at /home/myproj/node_modules/passport-facebook/lib/strategy.js:163:12
    at passBackControl (/home/myproj/node_modules/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:107:9)
    at IncomingMessage.<anonymous> (/home/myproj/node_modules/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:124:7)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:912:16
    at process._tickCallback (node.js:415:13)

pass more parameters

Hi,
I'd like to email users with a unique ID so when they log into my application via passport-facebook, they will be presented with information tailored to them (they'll go to a particular page with data pulled from my DB)

I was thinking of loading my login page with a hidden field containing that unique ID, and somewhat passing it through so when FB finishes authenticating, I could catch it on my side in /auth/facebook/callback.

Could anybody tell me how I could go about accomplishing this (or suggest a better way!)?

Deauthorize facebook callback

Hey! Curious if there is any integration for the facebook deauth callback that is fired when a user removes the app's permissions from their page. Thanks for the great module!

undefined refreshToken

I was just testing the example but in this part

  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    console.log(accessToken, refreshToken, profile, done);
    process.nextTick(function () {

      return done(null, profile);
    });
  }

i don't get a refreshToken (it is undefined). The other parameters are okay (accessToken, profile, done).

Has anybody the same problem or a solution for this problem?

Can't access user's email

The docs say that I can access the user's email through the profile object, but a console.log reveals

emails: [ { value: undefined } ],

access_denied errors not flashed

The connect-flash integration seems incomplete. If I try and use a bad ClientSecret, my error message is flashed OK. But, if I deny my app access to my Facebook profile, I get a proper callback from Facebook, but the error message is dropped and not passed through to passort/middleware/authenticate.js's failures array.

Callback:

http://localhost:3000/auth/facebook/callback?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.#_=_

passport module middleware/authenticate.js "failures" array:

[ { challenge: undefined, status: undefined } ]

Error: failed to parse user profile

I tried to use the passport-facebook module for facebook login by following the examples. After confirming the facebook login I land in an error page saying:

Error: Failed to parse user profile
at {blah blah}/passport-facebook/lib/strategy.js:163:12
at passBackControl ({blah blah}/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:107:9)
at IncomingMessage.<anonymous> ({blah blah}/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:124:7)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)

By looking at some console logs I added in the callback function, it seems that everything was normal in terms of accessToken and profile.

Facebook refresh token

I'm having trouble getting the refresh token back using the Facebook Strategy like in the example code. The access token comes back but my refresh token param in the callback is undefined. Am I doing something wrong? I saw there was a passport-facebook-offline module, should I use that one? I know with the google oauth2 you have to pass offline=true in the params to get back a refresh token.

thanks for the help,
-Matt

Is there a way to set the session expiration depending on the token expire

I have in my express configuration set up for session middleware

app.use(express.session({
      secret: 'somesecret',
      cookie: {httpOnly: false,  maxAge:  expiration},
      store: new mongoStore({
        url: config.db,
        collection : 'sessions'
      }),
      maxAge: expiration
    }));

can i call that app use in my passport use?

 passport.use(new FacebookStrategy({
                clientID: config.facebook.clientID
              , clientSecret: config.facebook.clientSecret
              , callbackURL: config.facebook.callbackURL
        },
        function (accessToken, refreshToken, params, profile, done) {

        //here
           var expiration = params.expire * 1000;
           app.use(express.session({
                secret: 'somesecret',
                cookie: {httpOnly: false,  maxAge:  expiration},
                store: new mongoStore({
                      url: config.db,
                      collection : 'sessions'
                }),
                maxAge: expiration
           }));
        });

Test users login.

Hi,

I add some users to Developer Roles as Test Users.

And the facebook API give you the access_token calling: "/APP_ID/accounts/test-users".

But i don't know how to login the as given user.
Other problem is where the "session - token" is stored I think it's a cookie, is there another way, like sending and extra parameter ?

Thanks!

More info: https://developers.facebook.com/docs/test_users/

facebook tab page

Hi,

I'm trying to get this working on a facebook tab page but doesn't work.

can someone give an exemple on how use passport-facebook to create canvas/tab page?

Thanks in advance.

Add support for re-auth authorization params

Please add support for 'auth_type' and 'auth_nonce' re-authentication params.

This works for me at line
https://github.com/jaredhanson/passport-facebook/blob/master/lib/passport-facebook/strategy.js#L71 :

Strategy.prototype.authorizationParams = function (options) {
  var params = {};

  if (options.display) {
    params['display'] = options.display;
  }
  if (options.auth_type) {
    params['auth_type'] = options.auth_type;
  }
  if (options.auth_nonce) {
    params['auth_nonce'] = options.auth_nonce;
  }

  return params;
};

undefined email in returned profile

When I receive the User Profile from Facebook, the emails array has one element inside, but its value is 'undefined'.

Is it a bug or is FB just not sending back the email address. Email is really the only thing we can use to associate the account with another account so it's essential we can get this from Facebook.

Thanks

How to determine whether new account or old account?

Inside my passport.use(new FacebookStrategy({ }); function, I will create and/or log in to an existing account.

Currently, once I get to callback, I redirect to index page for everyone, regardless of if they just signed up or found existing account.

Is there a way to set a flag in new FacebookStrategy() that can community with the "req" object in my callback, so that I can check whether the account is old or just created?

Thanks.

How to handle Facebook Invites with passport-facebook

How do we handle other actions with Facebook with passport-facebook? I'll use the example of friend invites.

Once our user is authenticated through Facebook and the profile is associated can we continue to use the retrieved access token and make requests? Or do we need to grab everything on the first request and pass it from form to form?

Deauthorize facebook callback

Hey! Curious if there is any integration for the facebook deauth callback that is fired when a user removes the app's permissions from their page. Thanks for the great module!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.