Facebook Connect and ASP.NET

I had a lot of trouble figuring out how to make server side calls once a user logged in with Facebook Connect. The key is that the Facebook Connect javascript sets cookies on the client once there’s a successful login. You use the values of these cookies to perform API calls on the server.

The confusing part was looking at the PHP sample they released. Their server side API automatically takes care of reading these cookie values and setting up an API object that’s ready to make requests on behalf of the logged in user.

Here’s an example using the Facebook Toolkit on the server after the user has logged in with Facebook Connect.

Server code:

API api = new API();
api.ApplicationKey = Utility.ApiKey();
api.SessionKey = Utility.SessionKey();
api.Secret = Utility.SecretKey();
api.uid = Utility.GetUserID();

facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;

foreach (facebook.Schema.user friend in api.friends.getUserObjects())
{
   // do something with the friend
}

Utility.cs

public static class Utility
{
    public static string ApiKey()
    {
        return ConfigurationManager.AppSettings["Facebook.API_Key"];
    }

    public static string SecretKey()
    {
        return ConfigurationManager.AppSettings["Facebook.Secret_Key"];
    }

    public static string SessionKey()
    {
        return GetFacebookCookie("session_key");
    }

    public static int GetUserID()
    {
        return int.Parse(GetFacebookCookie("user"));
    }

    private static string GetFacebookCookie(string name)
    {
        if (HttpContext.Current == null)
            throw new ApplicationException("HttpContext cannot be null.");

        string fullName = ApiKey() + "_" + name;
        if (HttpContext.Current.Request.Cookies[fullName] == null)
            throw new ApplicationException("Could not find facebook cookie named " + fullName);
        return HttpContext.Current.Request.Cookies[fullName].Value;
    }
}

Leave a Comment