Master Facebook OAuth in Node.js


Here we'll show you how to go through the Facebook OAuth process in Node.js, which lets any Facebook user log in to Facebook and grant your Node.js app access to their account. Our simple app logs users in and displays some info about their Facebook profile.

In order to follow this example, you'll need to have Node.js create an application server listening on http://127.0.0.1:4567.

Node does not restart its HTTP server on code change. To expedite your development process, we suggest you install Node Supervisor and use it to run your server.

Run our Facebook OAuth Example

1 Log in to Temboo. If you don't already have an account, you can register for free.

2 If you have not already, download and install the Node.js SDK as described in our getting started tutorial.

3 Create a new Facebook app via the Facebook developer console using the Apps menu at the top of the page. Once you've created a new App, click the Settings tab on the left, select + Add Platform, and choose the Website option. Set up your Temboo callback URL by specifying the following URL as your Site URL:

https://ACCOUNT_NAME.temboolive.com/callback/

4 Create a file called fboauth.js in the same location as the node_modules directory that contains the Temboo SDK. Add the code below to the fboauth.js file, making sure to substitute in your Facebook app details.

var http = require('http');
var url = require('url');

var Session = require('temboo/core/temboosession');
var FBOAuth = require('temboo/Library/Facebook/OAuth');
var FBRead = require("temboo/Library/Facebook/Reading");

// Set up variables that will be shared across responses.
// Set up a Temboo session for use by your Node.js server.
var session = new Session.TembooSession('ACCOUNT_NAME', 'APP_NAME', 'APP_KEY');

// Enter values from your Facebook app.
var appID = 'YOUR_FACEBOOK_APP_ID';
var appSecret = 'YOUR_FACEBOOK_APP_SECRET';

// These will be set during execution.
var authURL = null;
var callbackID = null;
var accessToken = null;


var server = http.createServer(function(request, response) {
    var path = url.parse(request.url).pathname;
    response.writeHeader(200, {"Content-Type": "text/html"}); 

    if (path == '/login') {
        var initializeOAuthChoreo = new FBOAuth.InitializeOAuth(session);

        // Instantiate and populate the input set for the choreo
        var initializeOAuthInputs = initializeOAuthChoreo.newInputSet();

        // Set inputs
        initializeOAuthInputs.set_AppID(appID);
        initializeOAuthInputs.set_ForwardingURL('http://localhost:4567/finalize');

        // Run the choreo. Upon success, clear for Facebook interactions.
        initializeOAuthChoreo.execute(
            initializeOAuthInputs,
            function(results) {
                authURL = results.get_AuthorizationURL();
                callbackID = results.get_CallbackID();
                console.log(authURL);
                console.log(callbackID);
                console.log('Heading to %s.', authURL);
                response.writeHead(302, {'Location': authURL});
                response.end();
            },
            // On failure, give some hints as the where the problem lies.
            function(error) {
                console.log('Error during initialization.');
                console.log(error.type); 
                console.log(error.message);
                response.end('Something bad happend. See log for info.');
            }
        );
    } else if (path == '/finalize') {
        // Set up the choreo to finalize the OAuth process.
        var finalizeOAuthChoreo = new FBOAuth.FinalizeOAuth(session);
        // Instantiate and populate the input set for the choreo
        var finalizeOAuthInputs = finalizeOAuthChoreo.newInputSet();

        // Set inputs
        finalizeOAuthInputs.set_AppID(appID);
        finalizeOAuthInputs.set_AppSecret(appSecret);
        finalizeOAuthInputs.set_CallbackID(callbackID);
        // Run the choreo. Upon success, run another choreo to show user info.
        finalizeOAuthChoreo.execute(
            finalizeOAuthInputs,
            function(results) {
                // console.log('Received access token:');
                // console.log(results.get_AccessToken());
                accessToken = results.get_AccessToken();

                // Set up a choreo to display info about the user.
                var userChoreo = new FBRead.User(session);

                // Instantiate and populate the input set for the choreo
                var userInputs = userChoreo.newInputSet();
                userInputs.set_AccessToken(accessToken);

                // Run the choreo. Upon success display the returned info.
                userChoreo.execute(
                    userInputs,
                    function(results) {
                        // console.log(results.get_Response());
                        response.end(results.get_Response());
                    },
                    function(error) {
                        // On failure, give some hints as the where the problem lies.
                        console.log('Error during info retrieve.');
                        console.log(error.type); 
                        console.log(error.message);
                        response.end('Something bad happend. See log for info.');
                    }
                );
            },
            function(error) {
                // On failure, give some hints as the where the problem lies.
                console.log('Error during finalization.');
                console.log(error.type); 
                console.log(error.message);
                response.end('Something bad happend. See log for info.');
        });

    } else {
        response.end('Log in with <a href="login">Facebook</a>.<br />');
    }
});

server.listen(4567);

5 Next, we'll start the Node.js server by running the following command from your project location:

node fboauth.js

5 If you installed Supervisor to monitor your Node.js app, you will instead run:

supervisor fboauth.js

6 Now you should be able to browse to the following URL:

http://127.0.0.1:4567

7 Click Login with Facebook and go through the OAuth process.

8 Once you've been redirected to Facebook, you can log in and grant the application access to your Facebook account. At this point in the example, you should be redirected back to your application where you'll see the user profile information in JSON format. That's it!

Taking a closer look at the code

This example includes two main functions for completing the OAuth process:

In the initialize route, we get the Authorization URL and Callback ID:

Below is the function that generates the Callback ID and redirects the user to the Authorization URL:

if (path == '/login') {
    var initializeOAuthChoreo = new FBOAuth.InitializeOAuth(session);

    // Instantiate and populate the input set for the choreo
    var initializeOAuthInputs = initializeOAuthChoreo.newInputSet();

    // Set inputs
    initializeOAuthInputs.set_AppID(appID);
    initializeOAuthInputs.set_ForwardingURL('http://localhost:4567/finalize');

    // Run the choreo. Upon success, clear for Facebook interactions.
    initializeOAuthChoreo.execute(
        initializeOAuthInputs,
        function(results) {
            authURL = results.get_AuthorizationURL();
            callbackID = results.get_CallbackID();
            console.log(authURL);
            console.log(callbackID);
            console.log('Heading to %s.', authURL);
            response.writeHead(302, {'Location': authURL});
            response.end();
        },
        // On failure, give some hints as the where the problem lies.
        function(error) {
            console.log('Error during initialization.');
            console.log(error.type); 
            console.log(error.message);
            response.end('Something bad happened. See log for info.');
        }
    );
}

In the finalize route, we run the FinalizeOAuth Choreo and pass the returned access token to the Facebook > Reading > User Choreo to retrieve your user's profile information.

else if (path == '/finalize') {
// Set up the choreo to finalize the OAuth process.
var finalizeOAuthChoreo = new FBOAuth.FinalizeOAuth(session);
// Instantiate and populate the input set for the choreo
var finalizeOAuthInputs = finalizeOAuthChoreo.newInputSet();

// Set inputs
finalizeOAuthInputs.set_AppID(appID);
finalizeOAuthInputs.set_AppSecret(appSecret);
finalizeOAuthInputs.set_CallbackID(callbackID);
// Run the choreo. Upon success, run another choreo to show user info.
finalizeOAuthChoreo.execute(
    finalizeOAuthInputs,
    function(results) {
        // console.log('Received access token:');
        // console.log(results.get_AccessToken());
        accessToken = results.get_AccessToken();

        // Set up a choreo to display info about the user.
        var userChoreo = new FBRead.User(session);

        // Instantiate and populate the input set for the choreo
        var userInputs = userChoreo.newInputSet();
        userInputs.set_AccessToken(accessToken);

        // Run the choreo. Upon success display the returned info.
        userChoreo.execute(
            userInputs,
            function(results) {
                // console.log(results.get_Response());
                response.end(results.get_Response());
            },
            function(error) {
                // On failure, give some hints as the where the problem lies.
                console.log('Error during info retrieve.');
                console.log(error.type); 
                console.log(error.message);
                response.end('Something bad happend. See log for info.');
            }
        );
    },
    function(error) {
        // On failure, give some hints as the where the problem lies.
        console.log('Error during finalization.');
        console.log(error.type); 
        console.log(error.message);
        response.end('Something bad happend. See log for info.');
});

}

What's Next?

We're all finished! This Node.js application executes the OAuth flow, and retrieves information about your app's user. We have OAuth support for many of the other APIs in our Library.

Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.

Need help?

We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.


Back