In the same vein as my last post on obtaining a permanent Google session token, we also found a need for a permanent Facebook OAuth access token. In our case, we wanted to grab data from Facebook Insights for several pages on a scheduled cron without requiring the user to authenticate each time.
Here's how to pull it off.
First, create a new Facebook application if you haven't already, and construct the OAuth url. Determine which permissions your access token will need, and fill in the application ID. Ours looks like this:
https://graph.facebook.com/oauth/authorize?client_id=...&redirect_uri=http://liquid9.tv/&scope=read_insights,offline_access
There are two things to note about the above url. First, notice we specified redirect_uri as http://liquid9.tv/. The redirect_uri is the path to which the browser will be redirected after authentication. This can be almost anything, and we are only using it in our case so we can grab the code parameter from its querystring after redirection occurs. There is, however, one requirement for this path -- its domain must match the one specified in the "Site URL" and "Site Domain" values of your application's "Web Site" settings.
The second thing to note is the offline_access permission we appended to the scope. This is the key to a permanent Facebook access token. The offline_access permission removes the short expiration time from your access token and allows your application to make requests on behalf of the user at any time.
Copy the authentication url into your browser and authorize your application with Facebook. You will be redirected to a url that looks similar to this:
http://liquid9.tv/?code=...
The code parameter will be a very lengthy string of random characters. Copy this value and hang on to it for the construction of a new url. This url will turn the generated code into a valid access token for your application.
Fill in your application ID, application secret, redirect uri, and the code we just copied. Again, ours looks like this:
https://graph.facebook.com/oauth/access_token?client_id=...&client_secret=...&redirect_uri=http://liquid9.tv/&code=...
Open the url in your browser, and you should be presented a string with an access token parameter in it. The value after access_token= is the bit you will want to store for future requests, and it can be used indefinitely to authenticate your application with this user's session!
Once we have the token, how can it be used to make requests? In Python, we use Facebook's own python-sdk. Assuming we stored our access token in a setting called FB_ACCESS_TOKEN, we can use it in our application like so:
import facebook
from settings import FB_ACCESS_TOKEN
graph = facebook.GraphAPI(FB_ACCESS_TOKEN)
page = graph.get_object(...)
...
Read more about Facebook OAuth authentication here: http://developers.facebook.com/docs/authentication/