Search code examples
asp.netfacebookfacebooktoolkit

Facebook Connect and ASP.NET


I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works

In particular, the user has logged into facebook via Facebook Connect and their web session has been created. How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user. For example, I'd like to get the user's first name and last name.

Examples in the documentation are geared towards facebook applications, which this is not.

Update

Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API: http://developers.facebook.com/docs/


Solution

  • 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;
        }
    }