• Stars
    star
    1,281
  • Rank 35,406 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Facebook authentication strategy for Passport and Node.js.

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 β€’ 🧠 Understanding OAuth 2.0 β€’ ❀️ 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

More Repositories

1

passport

Simple, unobtrusive authentication for Node.js.
JavaScript
21,911
star
2

oauth2orize

OAuth 2.0 authorization server toolkit for Node.js.
JavaScript
3,417
star
3

passport-local

Username and password authentication strategy for Passport and Node.js.
JavaScript
2,669
star
4

connect-flash

Flash message middleware for Connect and Express.
JavaScript
1,225
star
5

passport-http-bearer

HTTP Bearer authentication strategy for Passport and Node.js.
JavaScript
946
star
6

locomotive

Powerful MVC web framework for Node.js.
JavaScript
892
star
7

passport-google-oauth2

Google authentication strategy for Passport and Node.js.
JavaScript
802
star
8

passport-google-oauth

Google authentication strategies for Passport and Node.js.
JavaScript
753
star
9

passport-oauth2

OAuth 2.0 authentication strategy for Passport and Node.js.
JavaScript
575
star
10

electrolyte

Elegant dependency injection for Node.js.
JavaScript
563
star
11

passport-github

GitHub authentication strategy for Passport and Node.js.
JavaScript
528
star
12

passport-twitter

Twitter authentication strategy for Passport and Node.js.
JavaScript
467
star
13

connect-ensure-login

Login session ensuring middleware for Connect and Express.
JavaScript
465
star
14

passport-http

HTTP Basic and Digest authentication strategies for Passport and Node.js.
JavaScript
265
star
15

passport-remember-me

Remember Me cookie authentication strategy for Passport and Node.js
JavaScript
217
star
16

oauthorize

OAuth service provider toolkit for Node.js.
JavaScript
200
star
17

deamdify

Browserify transform that converts AMD to CommonJS.
JavaScript
198
star
18

passport-openidconnect

OpenID Connect authentication strategy for Passport and Node.js.
JavaScript
181
star
19

passport-instagram

Instagram authentication strategy for Passport and Node.js.
JavaScript
172
star
20

passport-totp

TOTP authentication strategy for Passport and Node.js.
JavaScript
147
star
21

passport-google

Google (OpenID) authentication strategy for Passport and Node.js.
JavaScript
146
star
22

passport-linkedin

LinkedIn authentication strategy for Passport and Node.js.
JavaScript
141
star
23

passport-oauth

OAuth 1.0 and 2.0 authentication strategies for Passport and Node.js.
JavaScript
117
star
24

passport-strategy

An abstract class implementing Passport's strategy API.
Makefile
107
star
25

junction

Essential XMPP middleware for Node.js.
JavaScript
105
star
26

passport-openid

OpenID authentication strategy for Passport and Node.js.
JavaScript
100
star
27

passport-oauth2-client-password

OAuth 2.0 client password authentication strategy for Passport and Node.js.
JavaScript
96
star
28

kerouac

Poetic static site generator for Node.js.
JavaScript
82
star
29

utils-merge

merge() utility function
JavaScript
71
star
30

passport-http-oauth

HTTP OAuth authentication strategy for Passport and Node.js.
JavaScript
70
star
31

bootable

Easy application initialization for Node.js.
JavaScript
68
star
32

oauth2orize-openid

Extensions to support OpenID Connect with OAuth2orize.
JavaScript
62
star
33

passport-anonymous

Anonymous authentication strategy for Passport and Node.js.
Makefile
59
star
34

passport-browserid

BrowserID authentication strategy for Passport and Node.js.
JavaScript
53
star
35

passport-webauthn

WebAuthn authentication strategy for Passport.
JavaScript
38
star
36

passport-soundcloud

SoundCloud authentication strategy for Passport and Node.js.
JavaScript
38
star
37

passport-amazon

Amazon authentication strategy for Passport and Node.js.
JavaScript
37
star
38

node-parent-require

Require modules from parent modules.
JavaScript
35
star
39

passport-windowslive

Windows Live authentication strategy for Passport and Node.js.
JavaScript
34
star
40

chai-passport-strategy

Helpers for testing Passport strategies with the Chai assertion library.
JavaScript
33
star
41

passport-fitbit

Fitbit authentication strategy for Passport and Node.js.
JavaScript
32
star
42

passport-tumblr

Tumblr authentication strategy for Passport and Node.js.
JavaScript
30
star
43

passport-dropbox

Dropbox authentication strategy for Passport and Node.js.
JavaScript
29
star
44

passport-paypal-oauth

PayPal (OAuth) authentication strategy for Passport and Node.js.
JavaScript
28
star
45

passport-bitbucket

Bitbucket authentication strategy for Passport and Node.js.
JavaScript
26
star
46

passport-oauth1

OAuth 1.0 authentication strategy for Passport and Node.js.
JavaScript
23
star
47

node-notifications

A mechanism for dispatching notifications within a Node.js program.
JavaScript
22
star
48

passport-foursquare

Foursquare authentication strategy for Passport and Node.js.
JavaScript
22
star
49

passport-goodreads

Goodreads authentication strategy for Passport and Node.js.
JavaScript
21
star
50

passport-yahoo-oauth

Yahoo! (OAuth) authentication strategy for Passport and Node.js.
JavaScript
19
star
51

passport-persona

Mozilla Persona authentication strategy for Passport and Node.js.
JavaScript
19
star
52

locomotive-mongoose

Mongoose datastore adapter for Locomotive.
JavaScript
18
star
53

passport-runkeeper

RunKeeper authentication strategy for Passport and Node.js.
JavaScript
18
star
54

node-jsonsp

JSON stream parser for Node.js.
JavaScript
17
star
55

node-jsonrpc-tcp

JSON-RPC over TCP for Node.js.
JavaScript
16
star
56

passport-intuit-oauth

Intuit (OAuth) authentication strategy for Passport and Node.js.
JavaScript
15
star
57

passport-evernote

Evernote authentication strategy for Passport and Node.js.
JavaScript
15
star
58

passport-ethereum

Ethereum authentication strategy for Passport.
JavaScript
15
star
59

passport-meetup

Meetup authentication strategy for Passport and Node.js.
JavaScript
15
star
60

crane

Diligent work queue for Node.js.
JavaScript
13
star
61

rivet

Efficient build tool utilizing JavaScript and Node.js.
JavaScript
13
star
62

passport-google-openidconnect

Google authentication strategy for Passport and Node.js.
JavaScript
12
star
63

connect-powered-by

X-Powered-By header middleware for Connect.
JavaScript
11
star
64

passport-yammer

Yammer authentication strategy for Passport and Node.js.
JavaScript
11
star
65

passport-hotp

HOTP authentication strategy for Passport and Node.js.
JavaScript
11
star
66

passport-paypal

PayPal (OpenID) authentication strategy for Passport and Node.js.
JavaScript
10
star
67

js-sasl

SASL mechanism factory.
JavaScript
10
star
68

passport-intuit

Intuit (OpenID) authentication strategy for Passport and Node.js.
JavaScript
10
star
69

node-tokens

Encode and decode security tokens.
JavaScript
9
star
70

draft-oauth-mfa

9
star
71

passport-openstreetmap

OpenStreetMap authentication strategy for Passport and Node.js.
JavaScript
9
star
72

node-servicelocator

Central location to register and locate services within a Node.js application.
JavaScript
9
star
73

passport-dwolla

Dwolla authentication strategy for Passport and Node.js.
JavaScript
9
star
74

todos-fastify-sqlite

Todo app built with Node.js, Fastify, and SQLite.
CSS
9
star
75

passport-angellist

AngelList authentication strategy for Passport and Node.js.
JavaScript
8
star
76

make-node

Useful makefiles for developing Node.js packages.
Makefile
8
star
77

chai-connect-middleware

Helpers for testing Connect middleware with the Chai assertion library.
JavaScript
8
star
78

oauth2orize-mfa

Multi-Factor Authentication exchanges for OAuth2orize.
JavaScript
6
star
79

flowstate

Per-request state management middleware.
JavaScript
6
star
80

suitcss-utils-space

Utility classes for low-level CSS spacing traits
CSS
6
star
81

passport-familysearch

FamilySearch authentication strategy for Passport and Node.js.
JavaScript
6
star
82

passport-37signals

37signals authentication strategy for Passport and Node.js.
JavaScript
6
star
83

passport-fido-u2f

FIDO U2F authentication strategy for Passport and Node.js.
JavaScript
6
star
84

passport-rdio

Rdio authentication strategy for Passport and Node.js.
JavaScript
6
star
85

oauth2orize-pkce

Extensions to support Proof Key for Code Exchange with OAuth2orize.
JavaScript
6
star
86

node-ffi-ipmi

wrapping various ipmi related tools and libs for node via node-ffi @ https://github.com/rbranson/node-ffi.git
C
6
star
87

todos-express-sqlite

Todo app built with Node.js, Express, and SQLite.
CSS
5
star
88

node-functionpool

Provides a pool of functions that can be used to execute tasks in Node.js.
JavaScript
5
star
89

connect-lrdd

Link-based Resource Descriptor Document (LRDD) middleware for Connect.
JavaScript
5
star
90

dotfiles

$HOME
Shell
5
star
91

passport-vimeo

Vimeo authentication strategy for Passport and Node.js.
JavaScript
5
star
92

amd-resolve

A hookable AMD module resolution implementation.
JavaScript
5
star
93

passport-ssl-certificate

SSL certificate authentication strategy for Passport and Node.js.
JavaScript
5
star
94

node-nks-fs

Secure key services.
JavaScript
5
star
95

marked-engine

Express-compatible Markdown rendering powered by marked.
JavaScript
5
star
96

chai-oauth2orize-grant

Helpers for testing OAuth2orize grants with the Chai assertion library.
JavaScript
5
star
97

oauth2orize-device-code

Extensions to support device flow with OAuth2orize.
JavaScript
5
star
98

oauth2orize-redelegate

Token redelegation and chaining exchange for OAuth2orize.
JavaScript
5
star
99

passport-web3

Web3 authentication strategy for Passport.
JavaScript
5
star
100

pocket

A simple, small, file system-based data store for Node.js.
JavaScript
4
star