Here is the Simple oAuth C# working example

147 posts / 0 new
Last post
Fatih YASAR's picture
Joined: 2009-11-23
Nov 27, 2009
Here is the Simple oAuth C# working example

Hi Folks,I have created an example oAuth C# and ASP.NET implementation example project.I hope it will be help a lot of confused people. And someone when created the linkedin core api put request with c# (for example status update)could updated to me ?I tried to tell with four step oauth how to work with linkedin auth system.example project enclosed in this post Let me know if you have problem with this example.Good luckand working project screen shot.LinkedInAuth.rar.zip

Carlos Nunes's picture
Joined: 2009-11-24
Nov 27, 2009

Hi Fatih,Great work.Congratulations!!!Carlos

Dev Filmjamr's picture
Joined: 2009-11-23
Nov 27, 2009

Hi Fatih  i am following your sample code.  Can u explain the OAuth Redirect URL .Here i have given my app Url. (www.filmjamr.com)  Can we test API locally?

Fatih YASAR's picture
Joined: 2009-11-23
Nov 27, 2009

OAuth redirect url is : every oauth supported systems must have authentication url.And this url contains username, password, application approval screens. When the user username password ,authorization givin approval completed, this page automatically redirect to already defined callback url.Look at here (oAuth flow): http://developer.linkedin.com/node/1008 Taylor described step by step.

Fatih YASAR's picture
Joined: 2009-11-23
Nov 27, 2009

You are welcome carlos.I hope it will be help to you

Phani Sundar's picture
Joined: 2009-11-23
Nov 27, 2009

Hi Fatih YASAR,Thanks for the post atleast I could get the access token from your code. I need small help when I run the code and called the method WebRequestWithPut() I am still haunted by the same error .The remote server returned an error: (401) Unauthorized.Can you please help me where I am going wrong.Thanks In Advance,Phani...

Fatih YASAR's picture
Joined: 2009-11-23
Nov 27, 2009

Phani,You catch up my in progress code, it shouldn't be here : )Don't worry I'm working on WebRequestWithPut()  function, and this function is containing my spike test codes which ishow to invoke PUT requests with oAuth header from LinkedIn main api.If you invoke main api functions (exactly put accepted methods) of LinkedIn api from C#, pls updated to me.Gook luck

Joined: 2011-01-19
Jan 27, 2011

Hi fatihI was looking at your example and tried to edit it to allow a callback url  but nothing i seemed to try worked by any chance can you give me some advice on were exactly i would need to add the callback urlthanksMiguel

Chris Nichols
Joined: 2009-11-30
Nov 30, 2009

Hi,I've implemented the code in this thread as part of a .net mvc application. The oAuth seems to work fine but I receive a 401 error when I attempt to make a call to the profile API. The error is non-descript and simply states "The remote server returned an error: (401) Unauthorized". There is no xml message body or detail so I'm not sure how to move forward. I've stepped through the code and the app seems to be pulling the tokens. Any ideas?Thanks,Chris

Arnab Choudhuri's picture
Joined: 2011-03-28
Mar 28, 2011

hi,If you have got the mvc app working, I would appreciate if you could pass it on to the community specially me:)TxArnab

Ashrafur Rahaman's picture
Joined: 2009-11-29
Nov 29, 2009

Hello,I am getting the following exceptionThe remote server returned an error: (400) Bad Request.in that line responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());when I click on 'Create Authorization' button. Please help me in it.

Joined: 2009-12-24
Dec 24, 2009

Hi Ashrafur,I have downloaded the C# demo and got the exception like you. Did you get over it, can you share this with me, I need it urgent.Thanks so much for your help.Regards,Steve

Robin den Buurman's picture
Joined: 2009-11-26
Nov 29, 2009

Works like a charm on my machine. Thanks.

Phani Sundar's picture
Joined: 2009-11-23
Nov 29, 2009

Hey Robin,Can you share your code with me. Did you implement any of the core Linked API methods like search or profile retrieval or connections etc...THanks & Regards,Phani

Robin den Buurman's picture
Joined: 2009-11-26
Nov 30, 2009

I just used the example of Fatih. Works like a charm to get accesstoken. To actually get useable data I am looking at the other threads.

- -
Joined: 2009-11-30
Nov 30, 2009

Hi Fatih,I tried to run your code and I got  following exceptionThe remote server returned an error: (400) Bad Request.Do I need to get any permission from linkedin to use LinkedIn API

Phani Sundar's picture
Joined: 2009-11-23
Nov 30, 2009

Hi Subhash,Where are you getting this error?Have you created an application in Linked. If not please create an application which will return you the secret and API key.If you have already created give the values in the web.config file. and run teh application as per the steps given by Fatih. Also note that you need clikc on the link generated and provide your LinkedIn credentials to get the access. and then clikc on Get AccessToken which returns the AccessTokenKey and AccressTokenSecret.This works in my machine. Hope this helps u.Thanks & Regards,Phani...

- -
Joined: 2009-11-30
Nov 30, 2009

Hi Phani,Thanks for your response.I have created the app in linkedin and have set the API key and secret key in web.config. file.When i run application and click 'Create Authorization' button then i am gettingthe remote server returned an error: (400) Bad Request. exception.Do i need to get any permission to use LinkedIn API  because it is written in this link  http://www.linkedin.com/static?key=developers_apis  Regards,Subhash

Anonymous (not verified)
Nov 30, 2009

I can't help you with the C# question, however you should know that there is no approval required to use these open APIs.A 400 error denotes that the request was malformed in some way.  Often you can find the source of the error by looking at the HTTP response.

Fatih YASAR's picture
Joined: 2009-11-23
Dec 1, 2009

Subhash,Did you download my example application ? and did you change appkey, secret information on itself ?

Chris Nichols
Joined: 2009-11-30
Dec 1, 2009

I downloaded the example and the results are the same as what is described below. It will retrieve the autorization tokens but "WebRequestWithPut" does not work. I used Fiddler to view the packets and it appears the signature is not correct.PO /v1/people/~/current-status HTTP/1.1Content-Type: text/xmlAuthorization: OAuth realm="http://api.linkedin.com/",oauth_consumer_key: ZN91L0G5fsjJE0vGD8ROqmvH06RdOUuwTY0iSoY67YYbnEBPv7uX39dR3qKM,oauth_nonce: 1936197,oauth_signature: 9D851BB2-9A9D-407E-A0DB-60D470B2676A&http%3A%2F%2Fapi.linkedin.com%2Fv1%2Fpeople%2F~%2Fcurrent-status&oauth_consumer_key%3DZN91L06AC5G5fsjJE0vGD8ROqmvH06RdOUuwTY0iSoY67YYbnEBPv7uX39dR3qKM%26oauth_nonce%3D1259690902%26oauth_signature_method%3D1936197%26oauth_timestamp%3DPUT%26oauth_token%3D6XZqYaJ1j2ppx7p7_zGc4U4zH8awxvMnGHf3zSq_JF0TKpwK_4Fyi1LoVf9m4Ohu%26oauth_verifier%3D01189%26oauth_version%3D1.0,oauth_signature_method: HMAC-SHA1,oauth_timestamp: 1259690902,oauth_token: e36eecfe-2e29-4d2d-9925-37e2730fb09b,oauth_verifier: 01189,oauth_version: 1.0Host: api.linkedin.comContent-Length: 0If you check the documentation at http://developer.linkedin.com/node/1008 their key looks like:oauth_signature="yp39fCS0UJiI1nnmsE06C4A7AA8%3D"

Phani Sundar's picture
Joined: 2009-11-23
Dec 1, 2009

Hi Subhash,Check out the security if you are under any firewall, check if your firewall is blocking the requests.Phani...

Joined: 2010-11-22
Nov 23, 2010

hello,I am doing through all the posts and you have followed Fatih YASAR's code . I am doing the same. I got the two keys and kept in web config and downloaded everything. I ran default.aspx, and kept my keys value and pressed create authentication then i get this error in throw . "The remote server returned an error: (500) Internal Server Error.".I also turned off my firewall. Is there sommething I am missing??

Rahul C's picture
Joined: 2009-11-27
Dec 1, 2009

Hi Fatih YasarThanks alot for the post. I am able to get the access token using LinkedIn API. I will be greatful to you. If you can help to find out to grab the LinkedIn Profile url of a person after successful authenticationThanks  in advanceRahul.

- -
Joined: 2009-11-30
Dec 1, 2009

Hi ,I am getting the following error.oauth_acceptable_timestamps=1259737043401%2B-300000&oauth_problem=timestamp_refused

Fatih YASAR's picture
Joined: 2009-11-23
Dec 2, 2009

Hi Guys,Finally, as i promised i created an example project, this project contains oAuth and api call via GET, POST, PUT requests.I hope it will be help to you.http://developer.linkedin.com/thread/1230Regards

Anonymous (not verified)
Dec 4, 2009

Hi,I need to get all LinkedIn contacts for a given Linked in account to my application. Is it possible to implement this using javascript without using any server side code.My actual need is to import all the contacts of LinkedIn in the SalesForce account. Salesforce suports VisualForce and javascript. I did not find any examples of Linkedin in API with visualforce so I decided to go for javascript.But again I came to know that we can not host js based apis as they will not work in hosted environment because of the crossdomain related security issues.Is it true? Please guide me related to this. After lot of googling I did not find any link which can help me.Thanks in advance.

Dev Filmjamr's picture
Joined: 2009-11-23
Dec 8, 2009

Hi Fatih,I am Using your  sample code. I used following Api http://api.linkedin.com/v1/people/~/network/updates/key={NETWORK UPDATE KEY}/update-comments in your _oauth.APIWebRequest("GET", Api link here , null)  methodIt Generates 400  error code(Bad request).Any help or clue ??...Thanks in Advance...

David Quail's picture
Joined: 2009-12-01
Dec 14, 2009

Nice work on the sample!Has anyone successfully set an oauth_callback parameter for the request token?I'm working on a C# client app and would like to intercept the authorize request callback from an embedded web browser in a similar way that I did with an iPhone version using a webView.   Using your sample, I simply added the oauth_callback parameter to the signature base.  This creates a signature which includes the callback, and also adds the callback to the request header.  ie.        public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters)        {......   parameters.Add(new QueryParameter("oauth_callback","liconnect://success"));...I'm getting a 401.Before I got too far troubleshooting I thought I'd ask if anyone's been able to set the oauth_callback here.

Chris Nichols
Joined: 2009-11-30
Dec 14, 2009

I've attemtped to set the callback but have not been able to make it work. You can set it in the LinkedIn API settings which is not great but it gets the job done until I have time to figure out. Please post if you figure it out.

David Quail's picture
Joined: 2009-12-01
Dec 15, 2009

I've got it working and calling back to my custom uri which I'll handle in my webview.  It's going to be a bit of a refactor of the original sample code, but ultimately all I had to do was url encode the oauth_callback and add it to the params.  Before I'd forgotten to url encode so the api was choking.The new GenerateSignatureBase method (after my change but before my refactor looks like the following.  I'll post the completed version when I'm done later today.        public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters)        {            if (token == null)            {                token = string.Empty;            }             if (tokenSecret == null)            {                tokenSecret = string.Empty;            }             if (string.IsNullOrEmpty(consumerKey))            {                throw new ArgumentNullException("consumerKey");            }             if (string.IsNullOrEmpty(httpMethod))            {                throw new ArgumentNullException("httpMethod");            }             if (string.IsNullOrEmpty(signatureType))            {                throw new ArgumentNullException("signatureType");            }             normalizedUrl = null;            normalizedRequestParameters = null;             List<QueryParameter> parameters = GetQueryParameters(url.Query);            parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));            parameters.Add(new QueryParameter(OAuthNonceKey, nonce));            parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));            parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));            parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));            //Added for testing purposes:                        String callback = "liconnect://success";             parameters.Add(new QueryParameter(OAuthCallbackKey, UrlEncode(callback)));My embedded webview then will take action if the urlscheme being navigated to is liconnect and cache the token for later access token call.ie.         private void myWebBrowser_Navigating(object sender, NavigatingCancelEventArgs e)        {            this.addressTextBox.Text = e.Uri.ToString();            if (e.Uri.Scheme=="liconnect")                System.Windows.Forms.MessageBox.Show("Got a callback: "  + e.Uri.PathAndQuery);        }

David Quail's picture
Joined: 2009-12-01
Dec 17, 2009

I posted a working sample of a desktop c# test app to a different thread The sample uses an embedded webbrowser for authorization before it returns control to the application.http://developer.linkedin.com/thread/1346Hope that helps

erwin yulianto's picture
Joined: 2010-02-20
Feb 20, 2010

Thanks David, it save me.

Joined: 2009-12-24
Dec 24, 2009

Hi Fatih,I downloaded your demo and replace the API key, Secret key, but when I press button Create Authorization, I got the exception said that The remote server returned an error: (400) Bad Request. I know that currently linkedin does not support passing authorization in query string, is it the reason for this exception?I need it urgent. So please consult me how to get it over.Thank you very much.RegardsSteve

Adarsh Kini's picture
Joined: 2010-02-01
Mar 11, 2010

Steve, i changed my time to a way-past time and i got the same error as you.. Could the oauth_timestamp be wrong?-ady

Roei Bar's picture
Joined: 2010-03-16
Apr 16, 2010

This example DOES NOT WORK ANY MORE, it used to work, but it just stoped working. the autorizion redirect the user to linkedin home page and does not supply an oauth_verifier code in the url.i haven't found any other work around that allows me to connect to LinkedIn API ,can any one help me????

Gary Brewer's picture
Joined: 2009-11-23
Apr 18, 2010

I just tried it now and it's working fine. Maybe a temporary hiccup for you?

Anonymous (not verified)
Apr 19, 2010

It's possible that the authorization URL was not specified properly.  In that case you may end up hitting our CSRF protection, which does redirect you to our home page.We have modified our forms to support both www.linkedin.com and api.linkedin.com for the moment.  In the future we will redirect the initial page render to the correct URL.

Pradeep Mehta's picture
Joined: 2010-04-20
Apr 20, 2010

Here is the perfect code, its running very fine at my end.protected void Page_Load(object sender, EventArgs e)    {        string authLink = string.Empty;        int PersonId = 0;        if (Session["reuqestToken"] == null)        {            authLink = _oauth.AuthorizationLinkGet();            Session["reuqestToken"] = _oauth.Token;            Session["reuqestTokenSecret"] = _oauth.TokenSecret;            Session["oauthLink"] = authLink;            Response.Redirect(authLink);        }        string oauth_token = Request.QueryString["oauth_token"];        string oauth_verifier = Request.QueryString["oauth_verifier"];        if (oauth_token != null && oauth_verifier != null)        {            Session["oauth_token"] = oauth_token;            Session["oauth_verifier"] = oauth_verifier;            _oauth.Token = Session["oauth_token"].ToString();            _oauth.TokenSecret = Session["reuqestTokenSecret"].ToString();            _oauth.Verifier = Session["oauth_verifier"].ToString();            _oauth.AccessTokenGet(_oauth.Token);            string response = _oauth.APIWebRequest("GET", "https://api.linkedin.com/v1/people/~", null);            //txtApiResponse.Text = response;            string fName = string.Empty, lName = string.Empty, title = string.Empty, liId = string.Empty;            fName = response.Substring(response.IndexOf("<first-name>") + 12, response.IndexOf("</first-name>") - response.IndexOf("<first-name>") - 12);            lName = response.Substring(response.IndexOf("<last-name>") + 11, response.IndexOf("</last-name>") - response.IndexOf("<last-name>") - 11);            title = response.Substring(response.IndexOf("<headline>") + 10, response.IndexOf("</headline>") - response.IndexOf("<headline>") - 10);            liId = response.Substring(response.IndexOf(";key=") + 5, response.IndexOf("&amp;authToken") - response.IndexOf(";key=") - 5);            DVO.Person.Person _dvoPerson = new DVO.Person.Person();            BLL.Person.Person _bllPerson = new BLL.Person.Person();            PersonId = _bllPerson.GetPersonIDByConnectUserID("LI", liId);            if (PersonId == 0)            {               //Save your data            }            Session["PersonID"] = PersonId.ToString();            Response.Redirect("Page");        }    }

- -
Joined: 2010-05-20
May 20, 2010

Hi Fatih,Realy good work you have done. I apprecite your knowldge. I have one query for you, How can i post content form my site to linkedin. Just consider one textbox and post button i have, when i enter some content in textbox and click post button then content have posted to linkedin.Please help me this is urgent!Regards,AMOL

Moshe Fleidervish's picture
Joined: 2010-06-12
Jun 12, 2010

Hi,I tried Simple oAuth C# working examplem,but got error:{"The remote server returned an error: (400) Bad Request."}in WebResponseGet function.My tequest is:POST /LinkedInAuth/Default.aspx HTTP/1.1Host: localhost:8080User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.9) Gecko/20100315 MRA 5.4 (build 02647) Firefox/3.5.9 GTB7.0 (.NET CLR 3.5.30729)Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,ru;q=0.7,he;q=0.3Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveReferer: http://localhost:8080/LinkedInAuth/Default.aspxContent-Type: application/x-www-form-urlencodedContent-Length: 441__VIEWSTATE=%2FwEPDwUJNjI5MzkxMDE5ZGSYDcj28e3VJ6PDJfQaTf2lnpCt5A%3D%3D&__EVENTVALIDATION=%2FwEWDQKL%2BozTDALA%2FOf7BwKLn6uMBwL2tqSvBQKxmtT5CAKGwoyBAgLMhKe%2FAQKOheSZCALkibb2BwKpoImIBgLuu%2BKyAwL104OLDwL4l8jwCZgx1YYvOWPpEd1nKLa7r2nq07hB&btnCreateAuthorization=Create+Authorization&txtRequestToken=&txtTokenSecret=&txtoAuth_token=&txtoAuth_verifier=&txtAccessToken=&txtAccessTokenSecret=&txtStatus=Let+me+test+is+it+working+%3F&txtApiResponse=PLease help me.

syam s's picture
Joined: 2010-06-27
Jun 28, 2010

Thanks for the code ..I had used the code .But i got Http Reply as "The remote server returned an error: (500) Internal Server Error." when try to get acesskey ..I had save my  consumerKey and Consumer sceret in oAuthLinkedIn.cs ..please reply me urgent...

syam s's picture
Joined: 2010-06-27
Jun 28, 2010

Hi Faith YAsar ,I had downloladed your code and changed consumerKey  and  consumerSecret in the page  oAuthLinkedIn.cs and in app config page .But when i click on  create Authorisation ..Error Occurs as 400 BAd requuest ...Pl,ease reply ...;

Joined: 2010-07-19
Jul 23, 2010

Hi FaithThanks for this good example I am struggling with one thing I need help with getting the _oauth_verifier and trying to get it without actually having to click on the Authlink which is a hyperlink and it must do the whole verficiation in the code behind reqeusting that page without have to go to linkedin. If anyone can help please this is urgent......RegardsJehslo

Filip Stas's picture
Joined: 2010-08-23
Aug 31, 2010

Another good example is this article I wrote (and it does work, I'm using it in a project at the moment):http://www.suddenelfilio.net/2010/08/24/linkedin-oauth-using-hammock-in-csharp-asp-net/

Joined: 2010-07-26
Sep 27, 2010

The remote server returned an error: (400) Bad Request. 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.Net.WebException: The remote server returned an error: (400) Bad Request. Source Error:

Line 325:            finally
Line 326:            {
Line 327:                webRequest.GetResponse().GetResponseStream().Close();
Line 328:                responseReader.Close();
Line 329:                responseReader = null;

did anybody resolve this problem? im tired of going in circles and ive read a bunch of people having this problem but it hasnt been answered. please help! thanks in advance

Tony Triguero's picture
Joined: 2010-10-06
Oct 6, 2010

Is there a way to pass the ReturnUrl to the OAuth server?  My returnUrl is specific to the user that is giving access to the tool.  So giving a static url is not sufficient.  Thanks.

Joined: 2010-10-18
Oct 19, 2010

hi Fatih YASAR,i downloaded yr code. it works well while status update,get my profile details,get my conections, send message to myself.but it will showing errors while try to send message to my connections and get profile of my connection peoples,The error is 400 bad request remote server. i can't able to fetch profile details of my connection people itself by giving their id.could yu please help me....

Gene Arnold's picture
Joined: 2010-11-24
Nov 24, 2010

I could really use some help on how to dynamically add in the oauth_callback url. My application will be used on many different sites so I can not hard code the call back url from within LinkedIn. Right now I'm just trying to get your example working. Would I need to change this code?protected void btnCreateAuthorization_Click(object sender, EventArgs e)    {        string authLink = _oauth.AuthorizationLinkGet();        Application["reuqestToken"] = _oauth.Token;        Application["reuqestTokenSecret"] = _oauth.TokenSecret;        Application["oauthLink"] = authLink;        txtRequestToken.Text = _oauth.Token;        txtTokenSecret.Text = _oauth.TokenSecret;               hypAuthToken.NavigateUrl = authLink;        hypAuthToken.Text = authLink;    }

Gene Arnold's picture
Joined: 2010-11-24
Nov 28, 2010

could any one offer me some help please?

Joined: 2010-12-14
Dec 14, 2010

Hi,I want to search for profiles of people whom I am not connected to. How can I do that. I am always getting private in result. Is their any way to get the result. Please help. Its urgent. Regards,Prithveesh

Pages