Facebook Dialog OAuth Tutorial

What is Facebook Dialog OAuth ?

Using Facebook OAuth Dialog, Users can authorize your website/App and give permissions to your website/App to access their information. In this tutorial, I have provided PHP, Python code samples. For JavaScript, check the tutorial http://hayageek.com/facebook-javascript-sdk/

Before going to the tutorial check the working example:

Facebook Dialog OAuth Demo Download Facebook OAuth Source

Follow the below steps for Dailog OAuth tutorial.

Step1 : Creating Facebook App

Before using Facebook OAuth Dialog, you need to create an App in Facebook Developers site and  get App ID & Secret.

To create an App, Go to https://developers.facebook.com/apps/
Click on “Create New App” and fill all the App details as shown in the  below images.

createNewApp               Provide App details               WebsiteLoginDetails

Note: “Website with Facebook Login:” and “App Domains:” are mandatory fields you need to fill and that should match your domain name.

 

Step2 : Invoking Facebook OAuth Dailog

After getting App ID and App Secret you can start using OAuth Dialog. Facebook Dialog can be invoked by providing the below URL format to User.

http://www.facebook.com/dialog/oauth/?
                                  client_id=APP_ID
                                   &redirect_uri=REDIRECT_URL
                                   &state=RANDOM_NUMBER_PREVENT_CSRF
                                   &scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
                                   &response_type=RESPONSE_TYPE
APP_ID : is your Application ID 
REDIRECT_URL: After successful authorization,user is redirected to this URL
RANDOM_NUMBER_PREVENT_CSRF: Random number to avoid CSRF attacks
COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES: list of permission you are asking the user
RESPONSE_TYPE cane "code" or "token". By default RESPONSE_TYPE is "code".

Sample Dialog URL looks like:

 http://www.facebook.com/dialog/oauth/?
                    client_id=113455642165175&
                    redirect_uri=http://hayageek.com/examples/facebook-oauth/callback.php&
                    scope=email,read_friendlists
                    &state=RANDOM_NUMBER

Step 3: User Authoriaztion

After clicking the Dialog URL, user will be redirected to authorize the website as shown in the below image.

OAuthDailog

After authorization, user will be redirected to REDIRECT_URL specified in the Dialog URL and you will receive “code”/”token” as part of the GET request.

If you select RESPONSE_TYPE=code then redirect URL looks like

    REDIRECT_URL?       
           code=OAUTH_CODE_GENERATED_BY_FACEBOOK
           &state=YOUR_STATE_VALUE

  Example: http://hayageek.com/examples/facebook-oauth/callback.php?
                            state=RANDOM_NUMBER&
                            code=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

If you select RESPONSE_TYPE=token then redirect URL looks like:

REDIRECT_URL#
    access_token=USER_ACCESS_TOKEN
   &expires_in=NUMBER_OF_SECONDS_UNTIL_TOKEN_EXPIRES
   &state=YOUR_STATE_VALUE

Example: http://hayageek.com/examples/facebook-oauth/callback.php#
                               state=RANDOM_NUMBER&
                               access_token=XXXXXXXXXXXXXXXXXXXXX&
                               expires_in=XXXXXXXXXXX

Note: RESPONSE_TYPE=code is used in server-side(PHP/JSP/Python/PERL),  RESPONSE_TYPE=token is used in client-side( Javascript SDK, Android SDK)

Step 4: Getting User Access Token at server-side

After getting user’s authorization, you need to get User access token to make the API calls. Acces Token request looks like

 https://graph.facebook.com/oauth/access_token?
                                             client_id=APP_ID
                                             &redirect_uri=REDIRECT_URI
                                             &client_secret=APP_SECRET
                                             &code=OAUTH_CODE_GENERATED_BY_FACEBOOK

 

Below is the PHP function to get the access token:

function getAccessTokenDetails($app_id,$app_secret,$redirect_url,$code)
{

	$token_url = "https://graph.facebook.com/oauth/access_token?"
	  . "client_id=" . $app_id . "&redirect_uri=" . urlencode($redirect_url)
	  . "&client_secret=" . $app_secret . "&code=" . $code;

	$response = file_get_contents($token_url);
	$params = null;
	parse_str($response, $params); //parse name value pair

	return $params;
}

Step 5: Making the API call server-side using PHP

After getting the access token you can make API cal. Below is the PHP code to get user’s personal information.

function getUserDetails($access_token)
{
	$graph_url = "https://graph.facebook.com/me?access_token=". $access_token;
	$user = json_decode(file_get_contents($graph_url));
	if($user != null && isset($user->name))
		return $user;

	return null;
}

Note:

  •  redirect_uri must be same  when getting the code and access_token

state should be a random number. if your web page is cached, state will always. So to avoid caching for the page, you can add the following code at the start of your page.

header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );

Python Code for Facebook Dialog OAuth

import sys
import urllib2
import urllib
import json
import urlparse
def parse_str(str):
	nvps={};
	list = str.rsplit("&")
	for el in list:
		nvplist = el.rsplit("=")
		nvps[nvplist[0]]=nvplist[1]
	return nvps

def getAccessTokenDetails(app_id,app_secret,redirect_url,code):

	list ={}
	url =  "https://graph.facebook.com/oauth/access_token?client_id="+app_id+"&redirect_uri="+redirect_url+"&client_secret="+app_secret+"&code="+code;
	req = urllib2.Request(url)
	try: 
		response= urllib2.urlopen(req)
		str=response.read()
		#you can replace it with urlparse.parse_qs
		list = parse_str(str)

	except Exception, e:
		print e
	return list

def getUserDetails(access_token):
	list={}
	url = "https://graph.facebook.com/me?access_token="+access_token;
	req = urllib2.Request(url)
	try: 
		response= urllib2.urlopen(req)
		str=response.read()
		list = json.dumps(str)
	except Exception, e:
		print e

	return list
###########

APP_ID='YOUR APP ID'
APP_SECRET='YOUR APP SECRET'
REDIRECT_URL='YOUR APP REDIRECT URL'
CODE=''  ###HTTP GET Parameter received from Facebook 

details = getAccessTokenDetails(APP_ID,APP_SECRET,REDIRECT_URL,CODE)

if not details["access_token"] is None:
	jsonText =getUserDetails(details["access_token"])

	#######Load it twice... Need to check
	jsonText =json.loads(jsonText)
	userInfo =json.loads(jsonText)
	#######Load it twice... Need to check

	print "Name: "+ userInfo['name']
	print "id: "+ userInfo['id']
	print "link: "+ userInfo["link"]