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('&').Where(s => s.StartsWith("oauth_token=")).Single().Split('=')[1];
            string token_secret = response.Content.Split('&').Where(s => 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.

, , , , , , , ,

  • Pingback: Connect to facebook using ASP.NET, Facebook Graph API & Hammock | Suddenelfilio.net

  • Muhammad Kamran

    Hi in the above code Callback() method can you specify how you are getting the values of token, token_secret and verifier at line 7, 8 and 9.

  • http://www.suddenelfilio.net Suddenelfilio

    those are the result of the authorize method you can store them somewhere in the session or so. The code you see is a distilled version of my original code. What I do is i store the values in a database like mongodb between requests. so yes you will need to use some way of storing the result to be used again in the callback.

  • S Muhammadkamran

    Thanks for explaining…. I am to integrate my MS Dynamics CRM contact with Linkedin… May be you can suggest some thing or provide some help. The scenario is like this:

    I need to show Linkedin Profile inside CRM contact… I’ve done through opening the URL to linkedin public profile in contact user interface for CRM. Now the issue is that I’ve need to post someinformation (may be with images etc) to Linkedin profile. I know what to do from CRM to get the information to post onto Linkedin but just don’t seems to get how we will post it to Linkedin user page.

    Probably you can suggest some thing. Any help would be appreciated.

  • http://www.suddenelfilio.net Suddenelfilio

    This is the Linkedin api information on how to post information to a Linkedin profile: http://developer.linkedin.com/docs/DOC-1009

  • Simon

    Hi – I have basic access to the LinkedIn API working nicely through Hammock, but if I try to use the LinkedIn field selector syntax in a request I get a 401 Unauthorised error.

    So for example I can call “people/~/connections” to get the basic data about my connections, but if I call “people/~/connections:(id,first-name,last-name,industry)” I get an error. The same thing happens using the profile and search APIs – as soon as I try to select the fields I want I get an error.

    Can anyone help?

  • Abc

    great!

  • David

    Have implemented this, and i get back an oauth_token and an oauth_token_secret.

    How do you then use these to make API calls, keep getting back [unauthorized]. The token used in the OAuth request is not valid.

  • David

    Had more of a play around. This code worked for me for getting a user profile.

                var request3 = new RestRequest            {                Path = “~”            };            var credentials3 = new OAuthCredentials            {                Type = OAuthType.AccessToken,                SignatureMethod = OAuthSignatureMethod.HmacSha1,                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,                ConsumerKey = LinkedInApiKey,                ConsumerSecret = LinkedInApiSecret,                Token = oauth_token ,                TokenSecret = oauth_token_secret,                Verifier = requestVerifier,            };            var client3 = new RestClient()            {                Authority = “http://api.linkedin.com/v1/people/”,                Credentials = credentials3,                Method = WebMethod.Get            };            var MyInfo = client3.Request(request3);

  • Stnl Ibe

    I see that you people have inserted manually the verifier.How can I obtain my verify value? 

  • chetan thummar

    Hi,

    I want to integrate linkediin api in my application . i want job search, people search, connection search, profile search from my application. its working if i implement it in web application. but i want to implement same in wcf service. so how to authenticate, authorization, how to get access token and Verifier?
    application is in asp.net MVC C#.

    please give me suggesion.
    thanks in advance

  • Stnl Ibe

    Hi thummar follow th rest api guide of linkedin, i’m doing this same thing for a sharepoint portal

  • Eduardo

    I can’t access to hammock page in codeplex, when I tried redirects me to codeplex.com…Â
    you know why happens that?

    So… do you have another link  for download this project?

    Thanks and good post!

  • Rk05

    hi,
       I am rajesh and i am working to integrate linkedin api in my dotnet app.
       This is a great one and i thank u for sharing it.

       I could not locate the Hammock library for the dotnet app.

       Could you please let me know where can i get the Hammock library. If you could please send me the links to following mail:
    rajekasani05@gmail.com

  • http://www.suddenelfilio.net Suddenelfilio

    you can now find it at github: https://github.com/danielcrenna/hammock

  • http://www.suddenelfilio.net Suddenelfilio

    you can now find it at github: https://github.com/danielcrenna/hammock

  • Uday Karekallu

    can i get java code for that

  • uday

    can i get java code for the access of linkdin

  • Mizan_01340

    I think this will help you if you are using linked In Restful API from Asp.net MVC
    http://mrsarker.wordpress.com/2011/08/20/linkedin-rest-api-in-asp-net-mvc/

  • Vinay Jujama

    Hi david…I have done the same i am facing a problem near

    OAuthCredentialsRestClient missing the assembly reference Pls tell me how can i get out of this problem

  • RK05

    Thnx for ur help.
    I found it and it’s working.
     

  • Bryan

    You need to get the Hammock from git hub

  • http://www.facebook.com/people/Desmond-Lzw/1485306056 Desmond Lzw

    i have the exact problem! do you have a solution to this yet?