Connect to Facebook using ASP.NET, Facebook Graph API & Hammock


UPDATE: Hammock moved to github https://github.com/danielcrenna/hammock

A while ago I wrote a post on how to perform oAuth authentication against the LinkedIn API using Hammock. Today I want to show you how to use Hammock with the Facebook Graph API. The Graph API is a new way a developer can read and write data to Facebook. Facebook uses oAuth 2.0 which is a simpler version of the oAuth authentication I used in my previous article with LinkedIn. It uses SSL instead of relying on the URL signature schemes and token exchanges you see in oAuth 1.x

There are 3 steps:

  1. Redirect the visitor to the authorization page over at Facebook.com
  2. Handle the callback from Facebook.com
  3. Get an access_token from Facebook.com using the code parameter returned by Facebook.com in step 2

For more information about the exact details on authorization in the Graph API go to: http://developers.facebook.com/docs/api

So let’s begin. I created a Web application in Visual Studio .Net 2010 that looks like this:

As you can see there is not much on the page except for a button, an empty image and some text with “Unknown” values. The goal is that when your visitor clicks the “Connect to Facebook” button he/she gets redirect to Facebook.com to authorize your application and then you can get the profile picture, name and the visitor’s about text he/she filled in on Facebook.

When the visitor clicks the “Connect to Facebook” the following code is executed:


   protected void Button1_Click(object sender, EventArgs e)
   {
            string callbackUrl = "http://localhost/FacebookConnectWithHammock/";
            //Request offline access and publish to the users stream access.
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope=offline_access,publish_stream", ConfigurationManager.AppSettings["FacebookClientId"], callbackUrl));
   }

What this does is it will redirect the visitor to facebook to the authorization page. This specific authorization request asks foor “offline_access” and “publish_stream” rights. This means that the application can access your Facebook account while you are offline and it can also publish updates to your Facebook account. Other parameters are the “client_id” which you need to set to your application’s client id that was assigned to your application when you created it and the “redirect_uri” which tells Facebook where to redirect the visitor after he/she granted your application access. When this is the first time the visitor is authorizing your application he/she will see the following authorization page:

When the visitors clicks on the “Allow” button Facebook will redirect the visitor back to the “redirect_uri” parameter. Then arriving on the web server we will receive a code parameter that we need to use to get the access_token. Here is how the callback code looks:

First in the Page_Load we check if the current request is a callback from Facebook by verifying if the Request["code"] querystring parameter is not null or empty and when it is not we call the callback handling code:


 protected void Page_Load(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)
     {
          HandleFacebookCallback();
     }
 }

The HandleFacebookCallback method will use the “code” parameter to get an access token and then call the DisplayUserInformation method passing the received token. The DisplayUserInformation will make a request to the Graph API requesting information about the visitor that just authorized the application. It will show the profile picture, name of the visitor and the about text that is filled in on his/hers Facebook profile.


        private void HandleFacebookCallback()
        {
            string CallbackUrl = "http://localhost/FacebookConnectWithHammock/";
            var client = new RestClient { Authority = "https://graph.facebook.com/oauth/" };
            var request = new RestRequest { Path = "access_token" };

            request.AddParameter("client_id", ConfigurationManager.AppSettings["FacebookClientId"]);
            request.AddParameter("redirect_uri", CallbackUrl);
            request.AddParameter("client_secret", ConfigurationManager.AppSettings["FacebookApplicationSecret"]);
            request.AddParameter("code", Request["code"]);

            RestResponse response = client.Request(request);
            // A little helper to parse the querystrings.
            StringDictionary result = ParseQueryString(response.Content);
            string aToken = result["access_token"];

            DisplayUserInformation(aToken);
        }

        private void DisplayUserInformation(string sToken)
        {
            var client = new RestClient { Authority = "https://graph.facebook.com/" };
            var request = new RestRequest { Path = "me" };
            request.AddParameter("access_token", sToken);
            RestResponse response = client.Request(request);

           JavaScriptSerializer ser = new JavaScriptSerializer();
            var parsedResult = ser.Deserialize<FacebookUser>(response.Content);

            ProfilePic.ImageUrl = string.Format("http://graph.facebook.com/{0}/picture?type=large",parsedResult.id);
            NameLabel.Text = parsedResult.name;
            AboutLabel.Text = parsedResult.about;
        }

When all goes well it should a little like the picture below.

Okay the formatting may not be optimal, but you get the point on how you can use Hammock to interact with the Facebook Graph API.

You can download the sample code here: Download
Downloaded 1751 times

NOTE: if you want to use the sample you will need to create an application first to get your application client id and secret. For more on this go to: http://www.facebook.com/developers/

, , , , ,

  • Livingston

    you should add oAuth 2 support to Hammock. That would be a great addition

  • http://www.suddenelfilio.net Suddenelfilio

    Thanks for the suggestion, but I’m not one of the developers on the project.I’m just demonstrating on how to use Hammock for this scenario. I invite you to provide your suggestion about this over at hammock.codeplex.com

  • http://you.arenot.me Colin Wiseman

    Great post!! I taken a slight different approach and have built a small website, where the code rebuilds the json string from Facebook into .NET objects. You can view my post and download the start of a basic api here:

    http://you.arenot.me/2010/09/28/facebooks-graph-api-and-asp-net/

    (code is at the bottom of the article).

  • http://www.suddenelfilio.net Suddenelfilio

    You post is interesting. My goal was not to create an entire Facebook API supporting library as to just show how to use hammock for oAuth.

  • http://twitter.com/vedattaylan Vedat Taylan

    hi, very nice article. but I have a problem.
    After giving permission gives the following error. What is the problem?

    **********************************************************
    Value cannot be null.
    Parameter name: stringToUnescape

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentNullException: Value cannot be null.
    Parameter name: stringToUnescape

    Source Error:

    Line 59: var request = new RestRequest { Path = “me” };
    Line 60: request.AddParameter(“access_token”, sToken);
    Line 61: RestResponse response = client.Request(request); // the error is here
    Line 62:
    Line 63: JavaScriptSerializer ser = new JavaScriptSerializer();

  • Test

    Thanks for the post !

    However instead of your ParseQueryString() , you can use the native:
    HttpUtility.ParseQueryString(response.Content);

    -
    Robert

  • Umitcel

    how can i connect my facebook account from my web application get some info for example friend count and show on page

  • Mahmudrajaa

    can i have the sample code for facebook wall post

  • Userehk

    This is gonna be the dumbest question but I just want to confirm
    So we are actually using the new graph API here instead of old rest API from facebook?
    In this case, would the rest API from hammock be affected or outdated?

  • http://www.suddenelfilio.net Suddenelfilio

    As far as I know it is the graph API. Haven’t followed it for a while now…

  • Moahnq

    This works like a charm … you are my hero Suddenelfilio
    I gain some basic understanding from Facebook Graph API and Hammock Rest now :) Thank you man !!!

    Oh btw, so if you want to gather stuff from facebook, you do a request and receive via response. What about if you want to post a status update?

    var client = new RestClient { Authority = “https://graph.facebook.com/” };
    var request = new RestRequest { Path = “me/feed” };
    request.AddParameter(“access_token”, sToken);
    request.AddParameter(“message”, message);

    RestResponse response = client.Request(request);

    That’s what I attempted but it only gives back recent messages, it does not understand the request as a POST

  • E_arindam

    Where did you get “RestClient, RestRequest”, i dint get those classes under Facebook.Rest namespace.

    can you please explain ?

  • Mzpb01

    Nice! I was wondering if I can download the sample code from somewhere? Thx in advance!!

  • http://www.suddenelfilio.net Suddenelfilio

    i saw the download links did not work any more, fixed this