TIGblogs TIG | TIGblogs GROUP TIGBLOGS LOGIN SIGNUP
Vidicorp Blog
Vidicorp Blog
« previous 5


Implementing Facebook Authentication, PHP

Several benefits exist in adopting decentralized authentication schemes – reduction in  the number of clicks required for authentication, increased conversion rates and easy user-specific customization of services . This article discusses how you can log in users to your website using Facebook (decentralized) authentication schemes and the PHP SDK found on the Facebook developers website. To get a clearer picture, you can read the prequel articles follows on Decentralized Authentication and How Facebook Authentication Works.

 

  1. Setup a Facebook App Account. Obtain your App id, App secret
  2. Download and extract the Facebook PHP SDK into your php project folder .https://github.com/facebook/php-sdk/ . It contains 3 folders – examples (containing a brief sample on which this tutorial is built), src (contains the main php Facebook class), and tests (test cases).
  3. Create a single php (fbbutton.php) to generate the login request link and in .
    Contents of fbbutton.php is given below
  4. Create another file fbconnect.php to which the user will be redirected after authentication via Facebook. Contents

 

The Facebook login button can be downloaded here

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Facebook Post to StumbleUpon


July 6, 2011 | 10:07 AM Comments  0 comments

Tags:


Implementing Facebook Authentication using PHP

Several benefits exist in adopting decentralized authentication schemes –

reduction in  the number of clicks required for authentication, increased conversion rates and easy user-specific customization of services . This article discusses

how you can log in users to your website using Facebook (decentralized) authentication schemes and the PHP SDK found on the Facebook developers website. To get a

clearer picture, you can read the prequel articles  on Decentralized

Authentication and How Facebook Authentication Works.

  1. Setup a Facebook App Account. Obtain your App id, App secret
  2. Download and extract the Facebook PHP SDK into your php project folder .href="https://github.com/facebook/php-sdk/">https://github.com/facebook/php-sdk/ . It contains 3 folders – examples (containing a brief sample on which this

    tutorial is built), src (contains the main php Facebook class), and tests (test cases).

  3. Create a php file. fbconnect.php to generate the login button and displaythe details of the authenticated user.

FbConnect.php

<?php
// Include the Facebook sdk base file.
require 'fb/src/facebook.php';

// Create our Application instance
$facebook = new Facebook(array(
   'appId'  => '*****Your Appid*********',
  'secret' => '***Your App Secret*******',
));

// Get User ID if user is logged in
$user = $facebook->getUser();

// Given that this page is redirected after user login,
// We should have the required code/permission to request user details

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
	//Request current users details hopefully he allowed the app :)
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }

}

$loginUrl = $facebook->getLoginUrl(
	array(
		'scope'         => 'email',
	)
);
?>
<?php if ($user) {?>
<a href='<?php echo $facebook->getLogoutUrl(); ?>'>Logout</a><br />
<?php } else { ?>
<a href='<?php echo $loginUrl; ?>'><img src='http://vidicorp.org/images/fblogin.png' width='149' height='22' alt='Login With Facebook' /></a><br />

<?php
}
// Display User detials.
if ($user ):
	echo $user_profile['first_name'] . "<br />";
	echo $user_profile['last_name']  . "<br />";
	echo $user_profile['name']  . "<br />";
	echo $user_profile['id']  . "<br />";

	echo "<br /><br /> Full User Profile <br />" ;
	print_r($user_profile) ;
	echo "<br /><br />Available Permission <br />" ;
	$user_permissions = $facebook->api('/me/permissions');
	print_r($user_permissions) ;
	echo "<br /><br />User Notes (if shared) <br />" ;
	$user_permissions = $facebook->api('/me/notes');
	print_r($user_permissions) ;
    // Set up User session and redirect to appropriate home page ;
    //$logoutGoTo = "/profilespage";
    //header("Location: $logoutGoTo");
    //exit;
else:
  // If user is not logged in, print out error message
  if(isset($_REQUEST['error'])) {
	if ( $_REQUEST['error_reason'] == 'user_denied') {
		echo "<br />Oops! You have declined to login using Facebook. ";
	}else {
		echo "<br />Oops! Facebook  Error." . $_REQUEST['error_description']  ;
	}
  } else {
	  echo "<br />You are not Logged in" ;
  }
endif
?>

The Facebook PHP SDK simplifies much of the authentication process using simple calls on the main facebook class. First we include the main facebook.php file (found in

the src folder of the downloaded facebook php sdk). Next, we create an application instance using your Appid and App Secret (more about that in previous article)..

remember to enter them correctly.

$facebook = new Facebook(array(
   'appId'  => '**** AppId *************',
  'secret' => '******App Secret***********',
));

A login URL is generated using the getLoginURL() method.

$loginUrl = $facebook->getLoginUrl(
	array(
		'scope'         => 'email',
	)
);

The getLoginURL() method also generates  a state session variable which is checked to counter CSRF attacks. The scope parameter specifies permission request for the

user data you want to access. An optional redirect_uri parameter (not shown above) could also be specified to indicate the page to which the user is redirected after

authentication is completed via facebook. When it is not explicitly specified as above, the user is redirected back to the same page (fbconnect.php). Remember that the

more permissions you request, the less likely users will Allow your app.  Finally, use the generated url as a login link.

<a href='<?php echo $loginUrl; ?>'><img src='http://vidicorp.org/images/fblogin.png' width='149' height='22' alt='Login With Facebook' /></a><br />

The user is redirected to back the same fbconnect.php page after authentication via the facebook OAuth dialog. If authentication has been successful, an authorization

code URL variable should be available now. The api() method simply uses this code (obtained from the URL) to request an access token, verifies correctness of the state

session variable (to guard against CSRF attacks) and calls the facebook graph api in order to receive the users details in return. The method call

$user_profile = $facebook->api('/me');

is equivalent to accessing 

https://graph.facebook.com/me&access_token=**************  

https://graph.facebook.com/users_username

with the appropriate access token.

The result of the api method can then be accessed to obtain user details

echo $user_profile['first_name'] ;

. A logical step in your application after obtaining these details would be to create the user’s record (registration) in your  database using the obtained details and

start a session (login) for the authenticated user.

More information about a user can be obtained by making the api calls e.g
$facebook->api(‘/me/notes’); — Users Notes
$facebook->api(‘/me/friends’); — Users Friends
$facebook->api(‘/me/permissions’); — Users Available Permissions

Full list of available information via the graph api can be found here .
NOTE : You need to explicitly get the users permission in order to view their detail. E.g you should add user_notes to your scope

scope => email,user_notes,

parameter in order to successfully obtain the user’s email and notes information via the graph api. It may be available without requesting permissions only if the user

shares this information with everyone under his/her privacy settings.
Full list of permissions can be found here 

Download the Facebook login button image.
Download fbconnect.php here .

A live demo can also be found here. .

 

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Facebook Post to StumbleUpon


July 6, 2011 | 10:07 AM Comments  0 comments

Tags:


Facebook Authentication – A Simple PHP Implementation

Several benefits exist in adopting decentralized authentication schemes – reduction in  the number of clicks required for authentication, increased conversion rates and easy user-specific customization of services . Now, this article discusses how you can log in users to your website using Facebook (decentralized) authentication schemes and the PHP SDK found on the Facebook developers website.

How it Works

Facebook Authentication is built using OAuth2.0 framework and supports two main OAuth flows. – Server side and Client Side .The server side flow which is discussed in detail in this tutorial is used when the authentication call is made from your web server .e.g your php script, jsp script etc . The client side flow is used when the authentication call is made from the client browser running Javascript or a native mobile or desktop application. These authentication calls are handled by the Facebook Graph API (http://developers.facebook.com/docs/reference/api/) which provides access to all social objects (people, pages, groups, photos). In order to utilize the Facebook Authentication, you must create an App on the Facebook developer apps page. After this you obtain an App id, API Key, and App Secret which is used in the authentication process.

The Server Side Authentication Flow

From your website or app, a user clicks the “Login with Facebook” link and is redirected to the Facebook OAuth dialog where user authentication and app authorization takes place. When invoking the OAuth dialog, you must pass in your App id (the client_id parameter)  and a url  (the redirect_uri parameter) to which the users browser is redirected after app authorization is concluded .The redirect_uri must be within the same domain as the Site URL you specify in Web site tab of the Developer App.

  1. <span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">https://www.facebook.com/dialog/oauth?</span><span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">client_id=YOUR_APP_ID&amp;redirect_uri=YOUR_URL</span>

If the user is already logged in, Facebook validates the login cookie stored on the user’s browser, authenticating the user. If the user is not logged in, they are prompted to enter their credentials:

 

Once the user is successfully authenticated, the OAuth Dialog will prompt the user to authorize the app:

 

By default, the user is asked to authorize the app to access basic information that is available publicly or by default on Facebook. If your app needs more than this basic information to function, you must request specific permissions from the user. This is accomplished by adding a scope parameter to the OAuth Dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to user’s email address and their news feed:

 

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream

 

A full list of permissions is available here permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; it is  recommended that you only request the permissions you absolutely need for your app.

 

If the user presses Don’t Allow, your app is not authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with the following error information:

http://YOUR_URL?error_reason=user_denied&
     error=access_denied&error_description=The+user+denied+your+request.

If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with an authorization code:

http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER

With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.

In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at 

https://graph.facebook.com/oauth/access_token

. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will.

https://graph.facebook.com/oauth/access_token?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
     client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

If your app is successfully authenticated and the authorization code from the user is valid, the authorization server will return the access token:

 

In addition to the access token (the access_token parameter), the response contains the number of seconds until the token expires (the expires parameter)

 

 

Implementation

  1. Setup a Facebook App Account. Obtain your App secret
  2. Download and extract the Facebook PHP SDK into your php project folder .https://github.com/facebook/php-sdk/ . It contains 3 folders – examples (containing a brief sample on which this tutorial is built), src (contains the main php Facebook class), and tests (test cases).
  3. Create a single php (fbbutton.php) to generate the login request link .
    Contents of fbbutton.php is given below
  4. Create another file fbconnect.php to which the user will be redirected after authentication via Facebook. Contents

 

The Facebook login button can be downloaded here

Drawbacks to Facebook Login

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Facebook Post to StumbleUpon


July 6, 2011 | 9:07 AM Comments  0 comments

Tags:


How Facebook Authentication Works

Facebook Authentication is built using OAuth2.0 framework and supports two main OAuth flows. – Server side and Client Side .The server side flow which is discussed in detail in this tutorial is used when the authentication call is made from your web server .e.g your php script, jsp script etc . The client side flow is used when the authentication call is made from the client browser running Javascript or a native mobile or desktop application. These authentication calls are handled by the Facebook Graph API (http://developers.facebook.com/docs/reference/api/) which provides access to all social objects (people, pages, groups, photos). In order to utilize the Facebook Authentication, you must create an App accont on the Facebook developer apps page. After this you obtain an App id, API Key, and App Secret which is used in the authentication process.

The Server Side Authentication Flow

From your website or app, a user clicks the “Login with Facebook” link and is redirected to the Facebook OAuth dialog where user authentication and app authorization takes place. When invoking the OAuth dialog, you must pass in your App id (the client_id parameter)  and a url  (the redirect_uri parameter) to which the users browser is redirected after app authorization is concluded .The redirect_uri must be within the same domain as the Site URL you specify in Web site tab of the Developer App.

  1. https://www.facebook.com/dialog/oauth? client_id=YOUR_APP_ID&amp; redirect_uri=YOUR_URL

If the user is already logged in, Facebook validates the login cookie stored on the user’s browser, authenticating the user. If the user is not logged in, they are prompted to enter their credentials:

 

Facebook OAuth Dialog

Facebook OAuth Dialog Source : http://developers.facebook.com/docs/authentication/

 

 

Once the user is successfully authenticated, the OAuth Dialog will prompt the user to authorize the app:

 

Facebook App Authorization Source : http://developers.facebook.com/docs/authentication/

 

By default, the user is asked to authorize the app to access basic information that is available publicly or by default on Facebook. If your app needs more than this basic information to function, you must request specific permissions from the user. This is accomplished by adding a scope parameter to the OAuth Dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to user’s email address and their news feed:

  1. https://www.facebook.com/dialog/oauth? client_id=YOUR_APP_ID&amp; redirect_uri=YOUR_URL&amp; scope=email,read_stream

A full list of permissions is available here permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; it is  recommended that you only request the permissions you absolutely need for your app.

 

If the user presses Don’t Allow, your app is not authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with the following error information:

  1. http://YOUR_URL?error_reason=user_denied&amp; error=access_denied&amp; error_description=The+user+denied+your+request.

If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with an authorization code:

  1. http://YOUR_URL? code=A_CODE_GENERATED_BY_SERVER

With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.

In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at

  1. https://graph.facebook.com/oauth/access_token

. The app secret is available from the Developer App  page and should not be shared with anyone or embedded in any code that you will distribute.

  1. https://graph.facebook.com/oauth/access_token?
  2. client_id=YOUR_APP_ID&amp;redirect_uri=YOUR_URL&amp;
  3. client_secret=YOUR_APP_SECRET&amp;code=THE_CODE_FROM_ABOVE

If your app is successfully authenticated and the authorization code from the user is valid, the authorization server will return the access token.In addition to the access token (the access_token parameter), the response contains the number of seconds until the token expires (the expires parameter). Finally this accesstoken can then be used to make requests to the graph api and return details on the user who has just been authenticated.

An implementation of this process using PHP is provided in the next article

 

 

Drawbacks to Facebook Login

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Facebook Post to StumbleUpon


July 6, 2011 | 9:07 AM Comments  0 comments

Tags:


Decentralized Authentication Schemes

It has become a common trend to see large websites sporting a “Login with Facebook”, or “OpenID” button. Both of these Login/ Authencation technologies are examples of decentralized authentication. This article aims to discuss motivations for decentralized authentication, how it works, and the above mentioned authentication schemes as they are used today.

(P.S these schemes are routinely updated and this article is current as of July 2011)

Birth of decentralized Authentication

Authentication is simply the process of establishing the identity of a given user. Usually in web applications that provide customized/user-specific services, we usually want to authenticate each person and provide services suited to his/her preferences.

Classic standalone authentication schemes include a registration process (where you fill a long form .. username, password, first name, last name etc), a confirmation process (via email) and finally a login process. Given that email addresses are unique identifiers (two different people usually DON’T own the same email address), they serve very well as digital identifiers for each internet user. The confirmation process simply to ensure that each user has access to the email address provided (so that you don’t register using my email address and masquerade as me  :)  ). However there is significant inverse correlation between the length of the registration forms and conversion rates (number of people that actually complete the registration process without giving up) – users generally hate long registration forms . It is indeed a tiring (bordering on frustrating) scenario to visit 10 websites in a day and have to fill in 10 different “long” registration forms for each website to access their services! That being said, consider a scenario where you log into just one website, and you can ask that website to tell all other websites who you are, complete with your profile details in a secure manner. This scenario pretty much sums up what decentralized authentication is all about. Several smooth decentralized authentication schemes (e.g Openid, Facebook Authentication) have been developed to achieve easy authentication across several websites. The basic idea behind these is that you authenticate yourself with one main system, which (with your permission) authenticates you to other systems.

Open ID

OpenID Authentication

OpenID is an open standard that describes how users can be authenticated in a decentralized manner, obviating the need for services to provide their own ad hoc systems and allowing users to consolidate their digital identities (wikipedia)

In the case of OpenID a “provider” is the main system that authenticates users. As shown in the figure, a user is provides an OpenID value (a URL or XRL) to an external website where he/she wishes to login. The website contacts the provider which notifies the user of the exact information the external website is requesting. The user has the choice to authorize the authentication and information sharing. If yes, the external website obtains the users information (registration details and all) and saves the user the task of entering this information all over again. Several security measures are built into this elaborate process and more can be found on the OpenID website.

Facebook Authentication

Face book authentication simplifies the authentication process in a manner similar to OpenID. Users simply log into Facebook (authenticate), and now can ask Facebook to authenticate them with other external websites/services that require their information.
Facebook utilizes an IETF protocol OAuth 2.0 to selectively grant external websites/apps access to your information based on your permissions and for a given duration.

As explained on the Facebook developers website, Facebook Authentication is accomplished in 3 steps.

  • First, Facebook needs to authenticate the user. This ensures that the user is who they say they are.
  • Second, Facebook needs to authenticate the external website. This ensures that the user is giving their information to the intended external website and not someone else.
  • Lastly, the user must explicitly authorize the external website to access their information. This ensures that the user knows exactly what data they are disclosing to the site.

Is decentralized authentication a good idea?

Yes, it sure is! From the users point of view, decentralized authentication schemes definitely make a big difference by speeding up the registration and login process on multiple websites. From website owners point of view, decentralized authentication could mean higher conversion rates and with the introduction of a robust package like Facebook Authentication, it is easy to customize pages and provide a rich social experience. OpenID and Facebook Authentication are both secure and always notify the users on the exact information that will be shared with any external website. Users reprise the rights to share any of their information.

Good old registration pages?

Under some scenarios where privacy is paramount (e.g an intranets, payment solutions etc) or where you have no choice it may be better to stick with the traditional standalone registration form. An approach to make this more usable is to collect only basic information during registration and allow users update their profiles later. A good example is twitter – Username, email, password … and voila you’ve got an account!
An interesting discussion on number of fields in a registration form and conversion rates from the marketing perspective can be found here .

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Facebook Post to StumbleUpon


July 2, 2011 | 12:07 PM Comments  0 comments

Tags:


« previous 5


Vykthur's Profile

Vykthur's Friends


Latest Posts
Implementing Facebook...
Implementing Facebook...
How Facebook...
Facebook...
Decentralized...

Monthly Archive
July 2007
May 2010
September 2010
October 2010
November 2010
July 2011

Change Language


Tags Archive
opportunity personaldevelopment thirdworld youth

Filter By Type
Topics

Friends
'Yemisi
Adeshola
Cat
cheta
Chloe
Enigma
Enigma
Enigma
Enigma
Eta Eta Uso
Henry Ekwuruke
JayBruce
Maricarmen
nadia
Sara Donají
sarah
siddiqua
Simon
Timothy Ogene
Yaz


15191 views
Important Disclaimer