Introduction & Prerequisites
In previous articles we have focused on integrating with Facebook Connect and authenticating
using the most recent version of the Facebook Developer Toolkit, version 2.0. Please
review the following two articles before continuing if you are unclear on either
of these processes.
How to Integrate with Facebook Connect - Bill Konrad
How to Use the Facebook Developer Toolkit 2.0 - Bill Konrad
Assuming that you have read/understand both, this article is the next logical step.
We are going to examine how to connect to the Facebook API using the Facebook Developer
Toolkit 2.0 when a user successfully authenticates with Facebook Connect from your
3rd party site. While the process is not complicated, it does require a bit of trickery.
So let's dive right in!
Getting Started
We are going to use the barebones project we created in
How to Integrate with Facebook Connect for the basis of this project. Listed
below is Default.aspx which will serve as our only .aspx page.
Default.aspx
<%@ page language="C#" autoeventwireup="true" codefile="Default.aspx.cs" inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head runat="server">
<title>Facebook Connect & Facebook Developer Toolkit 2.0</title>
</head>
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
type="text/javascript"></script>
<form id="form1" runat="server">
<div>
<fb:login-button length="long" onlogin="window.location.reload()">
</fb:login-button>
<br />
<br />
Name captured from Facebook Connect:
<asp:label id="lblName" runat="server" text="Not authenticated."></asp:label>
</div>
</form>
<script type="text/javascript">
FB.init("8a4e7b49b58938fdda19230224389297", "xd_receiver.htm");
</script>
</body>
</html>
There are only two items here that have changed since the original Facebook Connect
tutorial.
First, I have hooked in to the onlogin event with a quick JavaScript call to "window.location.reload()".
What this essentiallyl states is "when a Facebook Connect user successfully authenticates,
reload the current page." We do this so that our code behind file can capture the
result and use that data to connect to the Facebook API using the Facebook Developer
Toolkit. We'll see more on this later in the article.
The second is the asp:Label that I have added to display the full name of the successfully
authenticated user.
Capturing the Facebook Connect Authentication Results
The key to this article is understanding the next few steps. When a user authenticates
through Facebook Connect, a collection of cookies are set in the browser of the
client. They are as follows.
- APIKEY_user
- The user ID of the currently logged in user.
- APIKEY_session_key
- The current session. This is used to make API requests.
- APIKEY_expires
- When the current session expires. This is usually an hour or two after it's granted. If it's 0, then it means the session does not expire.
- APIKEY_ss
- The session secret. This prevents someone who knows your session key from using the session.
- APIKEY (with nothing after it)
- The signature, which will be generated from all other parameters.
- fbsetting_APIKEY
- The last cookie is not related to the signature validation (which is why it does not start with the APIKEY prefix). It is used to cache the login state between page loads, so that the XFBML rendering does not have to wait for a round trip to Facebook before starting.
The first two cookies listed here, APIKEY_user and APIKEY_session_key are the two we will primarily concern ourselves with. Let's take a look at the class ConnectAuthentication which I created to automate the process. Note, this class is based on ideas sourced from around the web in addition to my own ingenuity!
public class ConnectAuthentication
{
public ConnectAuthentication()
{
}
public static bool isConnected()
{
return (SessionKey != null && UserID != -1);
}
public static string ApiKey
{
get
{
return ConfigurationManager.AppSettings["APIKey"];
}
}
public static string SecretKey
{
get
{
return ConfigurationManager.AppSettings["Secret"];
}
}
public static string SessionKey
{
get
{
return GetFacebookCookie("session_key");
}
}
public static int UserID
{
get
{
int userID = -1;
int.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}
private static string GetFacebookCookie(string cookieName)
{
string retString = null;
string fullCookie = ApiKey + "_" + cookieName;
if (HttpContext.Current.Request.Cookies[fullCookie] != null)
retString = HttpContext.Current.Request.Cookies[fullCookie].Value;
return retString;
}
}
Rather than go into the nitty gritty details of how this works, let's take a look at how this class gets used to create the link between Facebook Connect and the Facebook Developer Toolkit. Below is a complete listing of Default.aspx.cs which contains the magic.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using facebook;
using facebook.web;
public partial class _Default: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (ConnectAuthentication.isConnected())
{
API api = new API();
api.ApplicationKey = ConnectAuthentication.ApiKey;
api.SessionKey = ConnectAuthentication.SessionKey;
api.Secret = ConnectAuthentication.SecretKey;
api.uid = ConnectAuthentication.UserID;
//Display user data captured from the Facebook API.
facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;
lblName.Text = fullName;
}
else
{
//Facebook Connect not authenticated, proceed as usual.
}
}
}
Just like a normal ASP.NET page lifecycle, we tap into the Page_Load event handler.
By calling ConnectAuthentication.isConnected() we quickly check to see if a Facebook
Connect user is currently authenticated. Then, taking a page out of
How to Use the Facebook Developer Toolkit 2.0 we set a collection of attributes
on the API object to let the Facebook API know who we are. We are now fully connected!
Not too bad, huh?
The rest is just to demonstrate to ourselves that we have actually connected to
the API. A quick call to api.users.getInfo() pulls down some profile data. We set
our asp:Label's text value to the full name of the authenticated user, and we are
done.
As is relatively self explanatory, the else statement here should contain any standard
Page_Load processing not pertaining to the Facebook API.
Conclusion & Next Steps
At this point, we have retrieved user data from the Facebook API based on user and
session data from a successful Facebook Connect authentication. There is no limit
to what can be accessed using the Facebook Developer Toolkit, so we essentially
have a full blown Facebook app in our third party site.
There is one piece of this that we are missing, and that is verifying the incoming
signature. While this is not particularly difficult, it gets a bit technical, and
is better suited to a new article. I'll follow up on this topic soon, and we'll
lock out the bad guys in style. Until then, go nuts, and enjoy your newly socially
leveraged web app!
