NOTE: I had a version of this blog post in draft mode for months addressing the old (PHP SDK v2.1.2) Facebook PHP library.  In a fit of momentum, I am publishing this post now, updated to use the new library (PHP SDK v3.1.1).  Since I am not as familiar with the new one, there may be better ways to do the following, although the code below works.

Facebook authentication, much like the rest of the platform, can be maddening.  It appears easy enough at 1st glance, until you realize the contrived XFBML examples in the docs will not get you very far.  So then you might take a look at the advanced document. And then realize that the advance document, that giant, complicated, very detailed and thorough explanation of OAuth 2.0 as implemented by Facebook, does not actually help you code your website.

This blog post is more for my benefit than yours, and serves to summarize my current Facebook authentication strategy, so I don’t have to figure it out over and over. At least, until Facebook changes it.

My Requirements

First off, realize that there are 3 ways to do any particular thing on the Facebook platform: XFBML, JS, and PHP (server-side).

That said, I do not use the XFBML <fb:login/> button.  XFBML is great for non-developers who can copy and paste the documentation into a website and impress their friends.  But XFBML is slower, ties your user’s application session to your user’s Facebook session, and you can’t make general API calls, so you may as well learn how to use the JS or PHP SDKs anyway.

  1. Authentication flow must work with and without JavaScript, as we are targeting older smart phones, such as Blackberry Curves.
  2. I do not want to use Facebook to persist my application sessions.  I merely want to use Facebook for authentication and then use standard PHP sessions to maintain a user login.  Using the Facebook session as your application session (as in the case of XFBML above) is sucky.  You will noticed sites that do this because when you log out of the site, you will log out of Facebook, and vice-versa.  Logging out of your site should not log you out of Facebook.  Facebook sessions and your application’s session should be separate.  I want to use Facebook only to authenticate the user, that is, to confirm the user is who they say they are.  Foursquare does a great job of this.

Implementation

First, I need a login login link that non-JS browsers can use.

<a id="fb-login" href="<?= $loginUrl ?>">Login</a>

That $loginUrl comes from:

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

The login link will ask the user for offline_access permission, as an example.

Then we need some the FB JS SDK to handle the link for those of us with modern browsers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
FB.init( { appId: 'XXXXXX', status: true, cookie: false, oauth: true } );
 
$('#fb-login').click(function(e) {
  e.preventDefault();
 
  FB.getLoginStatus(function(response) {
 
    // maintain application anchor/query string, if any
    q = window.location.search.substring(1);
    if (window.location.hash) {
      q = window.location.hash.split('?')[1];
    }
 
    // if already logged in, redirect
    if (response.authResponse) {
      window.location.href = '/?signed_request=' + response.authResponse.signedRequest + '&' + q;
 
    } else {
 
      // else present user with FB auth popup
      FB.login(function(response) {
 
        // if user logs in successfully, redirect
        if (response.authResponse) {
          window.location.href = '/?signed_request=' + response.authResponse.signedRequest + '&' + q;
        }
      }, { scope:'offline_access' } );
    }
  });
});

Couple interesting things to point out:

  1. In the call to FB.init(), the cookie flag is set to false.  In most FB examples, this flag is set to true.  If this flag is true, the JS will set a cookie (that begins with ‘fbsr_’) that will keep the user connected to your Facebook app during a browser session.  This can confuse your app, because if you do not clear this cookie when your user logs out, your app may automatically re-authenticate your user.  If you do intend to use your user’s Facebook session as your website’s session, set this flag to true.
  2. On lines 16 and 25, as in most FB examples, a simple window.location.reload() might appear.  This only works if the JS sets the Facebook cookie, as this cookie will tell the server that the user is authenticated after the reload.  Since we can’t use the cookie, we need another way to tell the server if this login attempt was successful.

Server side

On the server-side, Facebook will tell us if this user is who he says he is with the getUser() method.  If this method returns a non-zero user ID, then Facebook has authenticated this user, and we can create a normal PHP login session, however you usually do that.

$id = $facebook->getUser();
 
if ($id)
{
    // login successful
    $_SESSION['user'] = $id;
}
 
// redirect to user dashboard or something
header('HTTP/1.1 302 Found');
header('Location: /');
exit;

getUser() tries to authenticate a few different ways.  You can read the code in the PHP SDK if you’re really curious. One way is from the ‘fbsr_’ cookie.  Another is by checking for the signed_request in the query string.  Remember when we passed that in earlier via JS?   The cool thing is, that even in the non-JS case, Facebook will send that signed_request in the query string, so this code will function the same in both cases.

Keeping the user logged in as he makes requests is the same as usual.  I simply check for the flag (or, in the example above, a user ID) to verify authenticated status.

To logout, I can simply clear the PHP session like normal.

// logout
session_unset();
session_destroy();
 
// redirect to external home page
header('HTTP/1.1 302 Found');
header('Location: /');
exit;

Again, this does not log me out of Facebook

Conclusion

When might you want to use your user’s Facebook session for your user’s website session?  I think the only case you would do that is if your web app is a Facebook-centric application.  That is, if every feature of your app involves Facebook somehow. In that case, maybe it makes sense because your user cannot use your app without being connected to Facebook.

You can find a fully working example of this flow on my GitHub.  This really belongs in an MVC-type framework, but for simplicity I put everything in a giant if/else statement.  Throw the files in a webroot, add your app’s ID and secret to the PHP file, and try it out. Try it with JavaScript enabled and disabled.  After logging into the example, try logging out of Facebook, and then logging out of the example, and vice-versa. And let me know if you spot anything fishy.

Facebook: Upgrading to OAuth 2.0

As Facebook has beaten into me via my RSS reader over the last few months:

All apps must migrate to OAuth 2.0 for authentication and expect an encrypted access token. The old SDKs, including the old JS SDK and old iOS SDK will no longer work.

<digression> In the spirit of typical Facebook developer documentation, even this ostensibly unambiguous statement raises questions.  See, I have been using the “new” Graph API to authenticate for many months now, but not with the oauth flag set to true.  (In other words, I am on Oauth 1.0?)  Does this mean my code will break on Oct. 1st?  Or when they say that legacy authentication will break on Oct. 1st, do they mean that only the really old legacy auth will break?  In either case, I may as well upgrade to the latest and greatest now. </digression>

Here are the changes I had to make to get my stuff working with the oauth flag set to true.  They are mostly field and param name changes.  There may be other changes important to you, but this is what I needed to modify to upgrade.

1. Add ‘oauth: true‘ to FB.init()

So change this:

FB.init({ appId : XXXXXX });

to this:

FB.init({ appId : XXXXXX, oauth : true });

I infer from Facebook (which is usually dangerous) that this flag will be enabled for everyone on Oct. 1st.

2. Change ‘perms‘ to ‘scope

Anywhere you request permissions for your app upon Facebook login, you must change the ‘perms’ field to ‘scope’. So for a typical XFBML implementation, change this:

<fb:login-button perms=”offline_access”></fb:login-button>

to this:

<fb:login-button scope=”offline_access”></fb:login-button>

For a typical JS implementation, change this:

FB.login(function(response) { }, { perms : ‘offline_access’ });

to this:

FB.login(function(response) { }, { scope : ‘offline_access’ });

For a typical non-JS, server-side (PHP) implementation, change this:

<a href=”<?php echo $facebook->getLoginUrl(array(‘req_perms’ => ‘offline_acces's’)); ?>”>Connect with Facebook</a>

to this:

<a href=”<?php echo $facebook->getLoginUrl(array(‘scope’ => ‘offline_acces's’)); ?>”>Connect with Facebook</a>

3. Update JavaScript response object

Functions like FB.login() and FB.getLoginStatus() accept a callback that gets passed a response object from Facebook after an authentication attempt.  The previous response looked like this:

response = { perms : ‘offline_access’,
             session : {
               access_token : ‘XXXXXX’,
               base_domain : ‘mydomain.com,
               expires :0,
               secret : ‘XXXXXX’,
               session_key : ‘XXXXXX’,
               sig : ‘XXXXXX’,
               uid : ‘XXXXXX’ },
             status : ‘connected’ };

The new response looks like this:

response = { authResponse : {
               accessToken : ‘XXXXXX’,
               expiresIn : 0,
               signedRequest : ‘XXXXXX’,
               userID : ‘XXXXXX’ },
             status : ‘connected’ };

You must update your JS authentication logic accordingly.

4. Change server-side PHP call getSession() to getUser()

Versions of the PHP SDK prior to 3.0 had both a getSession() and a getUser() method. After 3.0, there is only the getUser() call.  If you were using getSession() to check for authentication previously, you must use getUser() now.  If you don’t care about the internals of the new SDK, then getUser() functions the same as before and returns the Facebook ID of the currently logged in user, or 0 if there is none.

If you do care about the new SDK, then the reason for this is because Facebook has done away with the session concept and embraced the OAuth2 signed_request concept instead.  For example, the JSON-ified session array is no longer passed back to your callback URL in the query string upon authentication.  Now, an encoded signed_request is passed back in the query string, which contains the same info (user ID, access token, expiration time, etc.)

5. Change server-side PHP Facebook class constructor

The new PHP Facebook class no longer accepts a cookie flag in the constructor.  If you don’t care about the internals of the new SDK, then remove the cookie flag and you’re done.

If you do care about the new SDK, then the reason for this – well, I’m not sure what the reason is.  Perhaps a commenter could enlighten me.  Best as I can tell, they have removed overlapping features of the the JS SDK and PHP SDK. Prior to OAuth2, both SDKs had cookie flags, and both could set and read the session cookie, which could be confusing, especially if you were persisting your own authentication cookie.  Now, the JS can still set and read the signed_request cookie, but the PHP library has gotten out of the cookie game (although it can still read a signed_request cookie set by JS, and now it stores the signed_request data in the PHP session).

One more note about cookie: the new Facebook cookie begins with ‘fbsr_’ and not ‘fbs_’.

Conclusion

That’s it. As I said, these worked for me, but YMMV. Happy upgrading!

Slides from tek11

Here are my slides from my two talks at PHP 2011 tek conference in Chicago, IL.  Slide PDFs and any demo code are on GitHub.  Recap to follow!

Of (PHP) Sessions, Cookies, and Authentication

Do you know the difference between the PHP config directives session.gc_maxlifetime and session.cookie_lifetime? Have you wrestled with implementing a “Remember Me” button on your login page? Learn how popular sites, such as Twitter and Facebook, keep you logged in (apparently) forever and the security risks of such methods.

Who’s Using Your Software?

Software is only successful if someone can use it. Good developers need to do more than just follow specifications, they need to visualize the people who will use it and understand what they need. Get to know your users and the questions you need to ask to make your implementation a success on all fronts.

I am nothing if not timely. 

Last month, Chris Shiflett proposed an excellent blog revival idea, wherein I am to write a blog in the month of March about why I like blogs.  Of the ones I managed to read, I liked this “Ideas of March” the best. As for me, well, we are halfway through April – but I started this draft in March?  Here were the rules:

  1. Write a post called Ideas of March.
  2. List some of the reasons you like blogs.
  3. Pledge to blog more the rest of the month.
  4. Share your thoughts on Twitter with the #ideasofmarch hashtag.

So here goes…

Way before I had a technology blog, I had a blog about local issues.  Local politics, sports, development, you name it.  I started that blog because I had a lot of opinions about development that was happening around me and issues that were balloted, and I couldn’t rob the world of my enlightened positions by keeping them to myself.   Blogs allow anyone with something to say to say it.

Blogs are ultimately social.  Before there were tweetups, there were blogger meetups. And it is very easy to have something to talk about when introducing yourself to someone (“Hey, I really liked your blog about…”).  Twitter has taken that “breaking the ice” concept to new levels, but it I’d much rather have someone come up to me and say that they’ve read my blog rather than say that they follow me.

Blogs are written, and writing is a good skill to practice.  If I have to write to explain something, then I have to know it well.  And with practice, the explanation gets better and clearer. Then other thoughts get better and clearer.  Then the world just gets better and clearer.

Oh, and blogs contain a crapload of useful information that solve all sorts of problems, or just spread interesting news.

In summary, I like blogs because:

  1. They give everyone a voice.
  2. They help people be more social.
  3. They help me improve my writing.
  4. They contain a crapload of useful information and news.

To round off the requirements, I pledge to blog more in this month of March, er – how about I just pledge to blog more?  And hopefully my RSS tweeter should get out the hashtag in the title.

:)

I recently came up a very steep learning curve using the Zend Framework (version 1.11.3). I had used components of ZF in the past with success, but this was the first time I had used Zend_Application for my core MVC.  I am no stranger to MVC frameworks in general, but I struggled with Zend.

My biggest source of confusion was the bootstrap process.  Namely, the autoloading of resources.  Yes, I followed the Zend Framework Quick Start and got my app up and running. Unfortunately, I didn’t actually know what was happening.  Finally, I came across this great question on Stackoverflow about bootstrapping the layout resource that pointed me in the right direction:

The line from application.ini

resources.layout[] = 

is equivalent to:

_initLayout() {}

in Bootstrap.php

Aha!  So now it was clear. There are two ways to initialize a resource in Zend:

  1. By adding one or more mysterious lines to your application.ini, or
  2. By constructing them with good old fashion code in a method that begins with “_init” in Bootstrap.php.

Option #1 bothers me.  Yes, it’s really cool that you can bootstrap a whole MVC application with no code and only a config file, but IMO that option should not be the recommended way for beginners and that options should most definitely not be used in any sort of “Quick Start” guide.  That sort of magic should be reserved for advanced users.  With a little more exploring, I found the code that initialized these resources in the non-trivial Zend_Application_Bootstrap_BootstrapAbstract class.  And I found all the built-in Zend resources in Zend/Application/Resource, which let me see which resources had which options and how to bootstrap them. 

On to option #2, my preferred way. If I want to initialize the Front Controller, I’ll just put this in the bootstrap file:

protected function _initFrontController()
{
    $front = Zend_Controller_Front::getInstance();
    $front->setControllerDirectory(APPLICATION_PATH . '/controllers');
    return $front;
}

If I want to enable and initialize the layout:

protected function _initLayout()
{
    $layout = Zend_Layout::startMvc();
    $layout->setLayoutPath(APPLICATION_PATH . '/layouts/scripts/');
    return $layout;
}

I really don’t mind carrying this around to every project.  Then I can make changes in the PHP, and not in an INI file.

Clearly I am not the only one struggling with this. I googled problems heavily and the top results usually contained 3 or 4 of the same question asked on Stackoverflow, each of which I opened in a tab.  I think Zend would benefit with a re-organization of the documentation from the ground up, at least of the starter docs and Zend_Application. They should also post a big, flashing red link to that Stackoverflow question about bootstrapping layout. 

Eventually, other components became clear: Resources, Plugins, Action Helpers, and View Helpers, Modules.  I see real power in using the Zend Framework now, particularly with Plugins and Modules, but only after much pain.

I have created a starter project for Zend projects that contains Bootstrap.php the way I like it, and some other custom classes for logging and error handling.  There is a branch for a starter project with modules and without modules.  (Modules is a different blog post altogether.)