Using Facebook to authenticate users to access your website or application is quite easy. In fact, based on the underlying OAuth you can provide your users a convenient way to authenticate with their existing Facebook credentials. This saves your users the hassle of remembering additional login credentials and possibly reduces the amount of data your system needs to store locally for each user.
So, here are the steps required to authenticate users through Facebook based on the tools and APIs provided by Facebook.
First, you need to register a Facebook application that users will authenticate with. So, in case you don’t already a one simply go to http://developers.facebook.com and so.
Hint: Make sure to not set it to public mode for now, as you probably don’t want your testing actions to be visible to your FB connections.
Second, you will need your application id and secret that you can access via http://developers.facebook.com.
Finally, you get to see some code. I’ve created a sample on GitHub. Go ahead and clone it.
This sample setup uses
to handle both, client- and server-side events.
Basically, we need to include the Facebook JavaScript SDK for client side events:
/** * Asynchronous Facebook JavaScript SDK inclusion. * Takes care of connecting event handlers and initial setup. * @returns {undefined} */ window.fbAsyncInit = function() { FB.init({ appId: '<?php echo FB_APP_ID; ?>', status: true, cookie: true, // enable cookies to allow the server to access the session xfbml: true // parse XFBML }); /** * connect event handler to user's FB authentication status * @type type */ FB.getLoginStatus(fbHandleSession); /** * here you can set to request additional permissions from your * user. Keep in mind that the more permissions you request the * higher is the chance that users will deny access to their * profile * @type Object */ var fbScope = {scope: 'email, user_location'}; jQuery('document').ready(function() { // ... }); /** * Here we subscribe to the auth.authResponseChange JavaScript * event. This event is fired for any authentication related * change, such as login, logout or session refresh. This means * that whenever someone who was previously logged out tries to * log in again, the correct case below will be handled. */ FB.Event.subscribe('auth.authResponseChange', function(response) { fbHandleSession(response); }); }; // Load the SDK asynchronously (function(d) { var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) { return; } js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/<?php echo $locale; ?>/all.js"; ref.parentNode.insertBefore(js, ref); } (document));
Next, we have our event handler functions:
/** * Handle FB login. * @param {Object} response * @see https://developers.facebook.com/docs/javascript/reference */ function fbHandleLogin(response) { console.debug('Hey there! We are quickly processing your login ' + 'request based on your FB authentication status...'); if (response.authResponse) { /** * we are simply refreshing to page for now so that we can * test the Facebook PHP SDK as well. * Feel free to update this event handler to your needs. */ window.location.reload(); } else { console.debug('Uups, it seems like our user did not finish ' + 'the login process'); } } /** * Handle FB register action. * @param {Object} response * https://developers.facebook.com/docs/javascript/reference */ function fbHandleRegister(response) { console.debug('Hey there! We are quickly processing your ' + 'register request based on your FB authentication status...'); if (response.authResponse) { /** * we are simply refreshing to page for now so that we can * test the Facebook PHP SDK as well. * Feel free to update this event handler to your needs. */ window.location.reload(); } else { console.debug('Uups, it seems like our user did not finish ' + 'the register process'); } } /** * Handles FB session status. * @param {Object} response * @see https://developers.facebook.com/docs/javascript/reference */ function fbHandleSession(response) { console.debug('Hey there! We are quickly checking your Facebook ' + 'login status for further actions...'); if (response.authResponse) { if (response.status === 'connected') { /** * our user is already logged in to FB and connected to * our app - great! * Let's handle the connected state. */ fbHandleConnected(response); } else if (response.status === 'not_authorized') { /** * our user is logged in to FB but not to our app. * We don't bother the user with login pop-ups or other * notifications at the moment. So let's silently * ignore this state. * Feel free to add status messages as needed here. */ console.debug('Welcome logged in FB user, ' + 'you might want to authenticate our app to ' + 'access all features?'); } else { /** * our user is not logged in to FB so we can't check for * possible app permissions we've set. * We don't bother the user with login pop-ups or other * notifications at the moment. So let's silently * ignore this state. * Feel free to add status messages as needed here. */ console.debug('Welcome user, ' + 'you might want to login to FB and ' + 'authenticate our app to access all features?'); } } else { console.debug('... welcome STRANGER!'); } } /** * Fetches user information. * Requires user to be logged in to FB and connection to app, i.e. * user has accepted scope permissions. * @param {Object} response * @see https://developers.facebook.com/docs/javascript/reference */ function fbHandleConnected(response) { console.log('Welcome! Fetching your information based ' + 'on scope permissions previously requested.... '); if (response.authResponse && response.status === 'connected') { /** * Let's request some user data to display. Feel free to adjust * this event handler to your needs ;) */ FB.api('/me', function(rsp) { console.log('Good to see you: ' + rsp.name + ' (' + rsp.email + ')'); }); } else { console.debug('Sorry, user is not logged in to FB and/or ' + 'connected to our app'); } }
And finally our server-side code, based on Facebook PHP SDK:
/** * Returns Facebook user if currently logged in, NULL otherwise. * @return object */ function getFacebookUser() { $facebook = new Facebook(array( 'appId' => FB_APP_ID, 'secret' => FB_APP_SECRET, )); $userId = $facebook->getUser(); if ($userId) { // We have a user ID, so probably a logged in user. // If not, we'll get an exception, which we handle below. try { $userProfile = $facebook->api('/me', 'GET'); return array( 'name' => $userProfile['name'], 'email' => $userProfile['email']); } catch (FacebookApiException $e) { // If the user is logged out, you can have a // user ID even though the access token is invalid. // In this case, we'll get an exception, so we'll // just ask the user to login again here. error_log($e->getType()); error_log($e->getMessage()); } } return NULL; }
This sample setup works by determining the authentication status of your users on the client side and additionally on the server side. It provides the default login button that comes with the Login social plugin, as well as incorporates two additional custom buttons:
- Custom login
- Custom register
In contrast to the default login button you can provide additional parameters for the event handlers hooked to these buttons, for instance scope permissions.
Feel free to play around with it and adjust it to your needs.
Leave a Reply