Posts Tagged hammock

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/

, , , , ,

14 Comments

LinkedIn OAuth using Hammock in C# & ASP.NET

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

 

Codeplex.com description of Hammock:
Hammock is a REST library for .NET that greatly simplifies consuming and wrapping RESTful services.

I’m currently working on a little web project that needed integration with LinkedIn.com. The LinkedIn API allows for OAuth authorization and authentication. They describe the process of getting a request token, authorizing it by the user and then getting an access token. Standard OAuth you might say. So I needed a way to do this in C# and found the Hammock library. Although Hammock does not only do OAuth I used it for that purpose only at the moment.

Below is the code I wrote to get a request token and send the user to the authorization page at Linkedin:


public void RequestAndAuthorize()
        {
            var credentials = new OAuthCredentials
            {
                CallbackUrl = "http://127.0.0.1/oauth/callback/",
                ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
                Verifier = "123456",
                Type = OAuthType.RequestToken
            };
            var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials };
            var request = new RestRequest { Path = "requestToken" };
            RestResponse response = client.Request(request);

            string token = response.Content.Split('&amp;').Where(s =&gt; s.StartsWith("oauth_token=")).Single().Split('=')[1];
            string token_secret = response.Content.Split('&amp;').Where(s =&gt; s.StartsWith("oauth_token_secret=")).Single().Split('=')[1];

            Response.Redirect("https://api.linkedin.com/uas/oauth?oauth_token=" + token);
        }

Once the user has authorized your request token the LinkedIn server will redirect the user back to the callback url in this case this is http://127.0.0.1/oauth/callback. Using the returned oauth_token and oauth_token_secret (you got this one while requesting a request token) you can now get an access token so you can start making authenticated API calls from you application on behalf of the user.

This is the code that is used when the callback url is called:


	public void Callback()
        {
            var credentials = new OAuthCredentials
            {
                ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
                Token = token,
                TokenSecret = token_secret,
                Verifier = verifier,
                Type = OAuthType.AccessToken,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                Version = "1.0"
            };
            var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials, Method = WebMethod.Post };
            var request = new RestRequest { Path = "accessToken" };
            RestResponse response = client.Request(request);
            string content = response.Content;
        }

As you can see Hammock is really nice and allows for easy OAuth authentication/authorization to be used.

, , , , , , , ,

23 Comments