Master Facebook OAuth in Python


Here we'll show you how to go through the Facebook OAuth process in Python, which lets any Facebook user log in to Facebook and grant your 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 Python 2.6.5 or higher and a Django web application server listening on http://127.0.0.1:8000/.

Get Set Up

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

2 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/

3 If you don't already have Django installed, you can use the following commands:

sudo easy_install pip
sudo pip install Django==1.6.2

Run our Facebook OAuth Example

4 Create a directory for this project, cd into the new directory, and run the following command:

django-admin.py startproject mysite

Running this command should create the following directory structure in your project folder:

5 Download the Temboo Python SDK and extract the ZIP file to the directory where you'd like to build this Python sample project.

6 Copy the following code into a new file called controller.py at this location: /mysite/mysite/controller.py:

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from config import FB_APP_ID, FB_APP_SECRET, FORWARDING_URL
from config import TEMBOO_ACCOUNT_NAME, TEMBOO_APP_NAME, TEMBOO_APP_KEY
from temboo.Library.Facebook.OAuth import InitializeOAuth
from temboo.Library.Facebook.OAuth import FinalizeOAuth
from temboo.Library.Facebook.Reading import User
from temboo.core.session import TembooSession
import uuid

# Create a Temboo session object
SESSION = TembooSession(TEMBOO_ACCOUNT_NAME, TEMBOO_APP_NAME, 
                        TEMBOO_APP_KEY)

def home(request):
    # Create links that triggers the getLoginUrl method
    return HttpResponse('''
        Login with <a href="login">Facebook</a>.<br />
    ''')

def get_login_url(request):

    # Generate a random state token which is used as the CustomCallbackID and in the ForwardingURL
    customCallbackId = str(uuid.uuid4())

    # Instantiate the InitializeOAuth choreo to begin the OAuth process.
    initializeOAuthChoreo = InitializeOAuth(SESSION)

    # Get an InputSet object for the InitializeOAuth choreo
    initializeOAuthInputs = initializeOAuthChoreo.new_input_set()

    # Set inputs for InitializeOAuth
    # Append the state token to the Forwarding URL
    initializeOAuthInputs.set_AppID(FB_APP_ID)
    initializeOAuthInputs.set_CustomCallbackID(customCallbackId)
    initializeOAuthInputs.set_ForwardingURL(FORWARDING_URL + "?state=" + TEMBOO_ACCOUNT_NAME + "/" + customCallbackId)

    # Execute InitializeOAuth choreo
    initializeOAuthResults = initializeOAuthChoreo.execute_with_results(initializeOAuthInputs)
    print "~~~~The Authorization URL is: " + initializeOAuthResults.get_AuthorizationURL()

    # Redirect user to the AuthorizationURL so that they can login and grant the application access
    return HttpResponseRedirect(initializeOAuthResults.get_AuthorizationURL())

def get_user_info(request):

    # Instantiate the FinalizeOAuth choreo
    finalizeOAuthChoreo = FinalizeOAuth(SESSION)

    # Get an InputSet object for the FinalizeOAuth choreo
    finalizeOAuthInputs = finalizeOAuthChoreo.new_input_set()

    # Set inputs for FinalizeOAuth
    # Get the state token parameter after the redirect to use as the CallbackID
    finalizeOAuthInputs.set_AppID(FB_APP_ID)
    finalizeOAuthInputs.set_AppSecret(FB_APP_SECRET)
    print "~~~~The state token is: " + request.GET.get('state')
    finalizeOAuthInputs.set_CallbackID(request.GET.get('state'))

    # Execute FinalizeOAuth choreo to complete the OAuth process and retrieve an access token
    finalizeOAuthResults = finalizeOAuthChoreo.execute_with_results(finalizeOAuthInputs)

    # Intiate the Facebook.Reading.User choreo to get the user's profile
    userChoreo = User(SESSION)

    # Get an InputSet object for the Facebook.Reading.User choreo
    userInputs = userChoreo.new_input_set()

    # Set the access token input
    userInputs.set_AccessToken(finalizeOAuthResults.get_AccessToken())

    # Execute Facebook.Reading.User choreo
    userResults = userChoreo.execute_with_results(userInputs)

    # Return user json and display it on the page
    return HttpResponse(userResults.get_Response(), mimetype='application/json')

7Create a new file called config.py at this location: /mysite/mysite/config.py. Fill in your Facebook and Temboo details. Your config.py file will look like this:

# Replace with your Facebook and Temboo credentials
FB_APP_ID = "YOUR_FACEBOOK_APP_ID"
FB_APP_SECRET = "YOUR_FACEBOOK_APP_SECRET"
TEMBOO_ACCOUNT_NAME = "ACCOUNT_NAME"
TEMBOO_APP_NAME = "APP_NAME"
TEMBOO_APP_KEY = "APP_KEY"
FORWARDING_URL = "http://127.0.0.1:8000/profile"

8 To call the functions in the controller, we need to map them to URLs. After you ran the startproject command in Step 2, a file called urls.py should have been created inside the mysite directory. Open urls.py in a text editor, and add the home, login/, and profile/ URLs shown below. The admin/ URL should already be there by default. Your urls.py file will look like this:

from django.conf.urls import patterns, include, url
import controller

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    # These URLs are necessary for this Temboo example
    url(r'^$', controller.home, name='home'),
    url(r'^login/', controller.get_login_url, name='login'),
    url(r'^profile/$', controller.get_user_info, name='profile')
)

9 Next, we'll start the Django application server by running the following command from within the /mysite directory:

python manage.py runserver

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

http://127.0.0.1:8000/

11 Click Login with Facebook link and go through the OAuth process.

12 Once you've been redirected to Facebook, you can log in and grant the application access. At this point, 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 get_login_url function, we generate a unique state token which can be handy in a couple ways:

Below is the function that generates the state token and redirects the user to the Authorization URL:

def get_login_url(request):

    # Generate a random state token which is used as the CustomCallbackID and in the ForwardingURL
    customCallbackId = str(uuid.uuid4())

    # Instantiate the InitializeOAuth choreo to begin the OAuth process
    initializeOAuthChoreo = InitializeOAuth(SESSION)

    # Get an InputSet object for the InitializeOAuth choreo
    initializeOAuthInputs = initializeOAuthChoreo.new_input_set()

    # Set inputs for InitializeOAuth
    # Append the state token to the Forwarding URL
    initializeOAuthInputs.set_AppID(FB_APP_ID)
    initializeOAuthInputs.set_CustomCallbackID(customCallbackId)
    initializeOAuthInputs.set_ForwardingURL(FORWARDING_URL + "?state=" + TEMBOO_ACCOUNT_NAME + "/" + customCallbackId)

    # Execute InitializeOAuth choreo
    initializeOAuthResults = initializeOAuthChoreo.execute_with_results(initializeOAuthInputs)
    print "~~~~The Authorization URL is: " + initializeOAuthResults.get_AuthorizationURL()

    # Redirect user to the AuthorizationURL so that they can login and grant the application access
    return HttpResponseRedirect(initializeOAuthResults.get_AuthorizationURL())

Note that we use the state token as the CustomCallbackID and as a parameter in the ForwardingURL.

The last step is to run the FinalizeOAuth Choreo and pass the returned access token to the Facebook > Reading > User Choreo to retrieve your user's profile information. The important thing to note here is that the state token is passed to this method from the page and used as the callback identifier in the FinalizeOAuth Choreo.

def get_user_info(request):

    # Instantiate the FinalizeOAuth choreo
    finalizeOAuthChoreo = FinalizeOAuth(SESSION)

    # Get an InputSet object for the FinalizeOAuth choreo
    finalizeOAuthInputs = finalizeOAuthChoreo.new_input_set()

    # Set inputs for FinalizeOAuth
    # Get the state token parameter after the redirect to use as the CallbackID
    finalizeOAuthInputs.set_AppID(FB_APP_ID)
    finalizeOAuthInputs.set_AppSecret(FB_APP_SECRET)
    print "~~~~The state token is: " + request.GET.get('state')
    finalizeOAuthInputs.set_CallbackID(request.GET.get('state'))

    # Execute FinalizeOAuth choreo to complete the OAuth process and retrieve an access token
    finalizeOAuthResults = finalizeOAuthChoreo.execute_with_results(finalizeOAuthInputs)

    # Intiate the Facebook.Reading.User choreo to get the user's profile
    userChoreo = User(SESSION)

    # Get an InputSet object for the Facebook.Reading.User choreo
    userInputs = userChoreo.new_input_set()

    # Set the access token input
    userInputs.set_AccessToken(finalizeOAuthResults.get_AccessToken())

    # Execute Facebook.Reading.User choreo
    userResults = userChoreo.execute_with_results(userInputs)

    # Return user json and display it on the page
    return HttpResponse(userResults.get_Response(), mimetype='application/json')

What's Next?

We're all finished! This Python application executes the Facebook OAuth flow, and retrieves information about your app's user. We have OAuth support for many 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