Twitter oAuth with .NET
I recently completed the conversion from Basic Authentication to oAuth for My Tweeple. Since there aren’t many .NET examples out there, I’ve attached an example application. As usual, you’ll need to convert it to meet your needs and apply appropriate error handling, but hopefully this will save someone a little time.
Download the full code here.
Update
Troubleshooting tips:
- Your application’s consumer key and secret should be entered in the web.config file. (from http://Twitter.com/oauth)
- The date/time on your machine must be accurate. Make sure you’ve performed a recent sync with a known time source.
- If you’re trying to call a Twitter API method that will update data, make sure the oAuth setup is Read/Write on Twitter.com/oAuth.
namespace oAuthExample { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string url = ""; string xml = ""; oAuthTwitter oAuth = new oAuthTwitter(); if (Request["oauth_token"] == null) { //Redirect the user to Twitter for authorization. //Using oauth_callback for local testing. oAuth.CallBackUrl = "http://localhost/"; Response.Redirect(oAuth.AuthorizationLinkGet()); } else { //Get the access token and secret. oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]); if (oAuth.TokenSecret.Length > 0) { //We now have the credentials, so make a call to the Twitter API. url = "http://twitter.com/account/verify_credentials.xml"; xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty); apiResponse.InnerHtml = Server.HtmlEncode(xml); //POST Test //url = "http://twitter.com/statuses/update.xml"; //xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("Hello @swhitley - Testing the .NET oAuth API")); //apiResponse.InnerHtml = Server.HtmlEncode(xml); } } } }
Thanks to Eran Sandler for his Basic oAuth Class which I happily extended for Twitter.
Related:
Twitter oAuth with .NET for the Desktop
data-url="http://www.voiceoftech.com/swhitley/index.php/2009/03/twitter-oauth-with-net/"
data-text="Twitter oAuth with .NET (Shannon Whitley)"
data-count="vertical"
>Tweet196 Responses to “Twitter oAuth with .NET”
Leave a Reply
54 Trackbacks
- swhitley (Shannon Whitley)
Twitter oAuth with .NET example code [New Post] – [link to post]– Posted using Chat Catcher
- akvalley (Anthony K. Valley)
@swhitley Thanks for the .NET sample code for Twitter oAuth [link to post]. I’ll use it to fix a PowerShell script I found.– Posted using Chat Catcher
- akvalley (Anthony K. Valley ©)
Twi… [link to post]– Posted using Chat Catcher
- cavalierandy (Randy Dillon)
Twitter oAuth with .NET [via FAQ] [link to post]– Posted using Chat Catcher
- send2moran (send2moran)
@gromer, try this class – [link to post] the important line is : oAuth.AccessTokenGet(Request["oauth_token"]);– Posted using Chat Catcher
- moomerman (Richard Taylor)
@aroxo its a couple of hours if you’ve already got a decent oauth lib to hand [link to post]– Posted using Chat Catcher
- ninjamonk (Darren Stuart)
working on an oAuth setup for .net and twitter, this helps [link to post]– Posted using Chat Catcher
- zerophyte (Cian H)
Reading a few things about twitter’s OAuth system – nothing new, just throught the api wiki – .NET example code : [link to post]– Posted using Chat Catcher
- SteveHolstad (Steve Holstad)
Excellent .NET Twitter oAuth class by @swhitley [link to post] Community dev at it’s best.– Posted using Chat Catcher
- Twitter OAuth in C# | Die In A Hole
[...] one example on the tubes (linked from Twitter’s OAuth wiki page), to Shannon Whitley’s blog post at Voice of Tech, where he explains how he did OAuth for My Tweeple, based on Eran Sandler’s [...]
- How to update on Twitter account from code?
[...] Was this link no use? Twitter oAuth with .NET | Shannon Whitley [...]
- Jeffbrown711 (Jeff Brown)
@ardalis u have any working snipits of something like this? [link to post]- Jeffbrown711 (Jeff Brown)
@ardalis looking to authenticate via oauth – missing something that is not allowing this to run [link to post]- ardalis (Steve Smith)
@Jeffbrown711 you just want some code that talks to twitter’s API in C#, or what?- Jeffbrown711 (Jeff Brown)
@swhitley where is the latest working version of [link to post]
– i am unable; to get this to work. thks- swhitley (Shannon Whitley)
@Jeffbrown711 E-mail me and maybe I can help with specifics.- swhitley (Shannon Whitley)
@Jeffbrown711 I believe this code still works: http://voiceoftech.com/downloads/oauthtwitterexamplenet.zip- mchid (mark chidlow)
oh the joys of oAuth .NET at [link to post]- mariusdima (md)
Hei! Twitter oAuth with .NET [link to post]- docblop (Mike Schaefer)
@stuartmanning there’s an oauth implementation for .net already. no need to reinvent the wheel. [link to post]- stuartmanning (Stuart Manning)
@docblop and it is ‘often’ used in CodePlex.com OAUTH contribute projects*great link*
- stuartmanning (Stuart Manning)
@docblop thanks =) there’s a ‘little’ more to do than just that example.. however it has ‘inspired’ alot of other to take this forward- docblop (Mike Schaefer)
@stuartmanning ok, just thought I’d point it out, but you obviously have it covered. Have used it and it works well for me. cheers![]()
- stuartmanning (Stuart Manning)
@docblop you too sir =) it ‘very easy’ to implement :: there is the 1.1 standard etc and REST =) all good, and nice to meet you- prakash1979 (prakash)
[link to post] via @addthis- chridam (Chris Dambamuromo)
Twitter oAuth with .NET [link to post] via @addthis- ahmd (ahmd)
[link to post]- MichaelApproved (Michael Khalili)
@BrandonWatson Recently setup OAuth with [link to post] and username/pass with Yedda http://bit.ly/10NPEI what you trying to do?- Test Message | Hidden Treasures Of . Net
[...] [...]
- jdmullin (J.D. Mullin)
@aarnott I started w Shannon Whitley’s, then modified it to be used in a WinForms app instead of an ASP.NET application. [link to post]- dixzan (Antonio Torres)
@lhchavez estoy aprendiendo como registrar mi API para consumir todos los servicios de Twitter. Se llama oAuth. [link to post].- lhchavez (lhchavez)
@dixzan aaah el oAuth… tuvieron broncas de seguridad con eso cuando lo sacaron por primera vez![]()
- GameTree » Blog Archive » Coding the Tweet, Redux
[...] code is still using Eran Sandler and Shannon Whitley’s oAuth/Twitter library but with additional changes to support the new PIN mechanism. If you have visions of .NET Twitter [...]
- +60 librerias .net que todo desarrollador debería conocer « Hablando de web Desarrollo ágil de web en php, asp.net, javascript…
[...] Whitley ofrece este ejemplo: Code | Live [...]
- Twitter oAuth with .NET for the Desktop | Shannon Whitley
[...] hope people have benefitted from my example application for Twitter oAuth in .NET. Occasionally someone will leave my Twitter name in the sample post and it pops up in my [...]
- Software Creations - Orn Kristjansson · #swBoulder 2010
[...] on that, now I know how that works. As we decided to use .net to code, I found code to reuse from .Net solution by Shannon Whitley [...]
- edenics (Daniel David)
![]()
“Twitter oAuth with .NET” (Shannon Whitley) [link to post] – a good article- yiyul00 (Yuri Yi)
![]()
Twitter oAuth with .NET (Shannon Whitley) [link to post]- Twitter oAuth with .NET | alessio ricco
[...] Twitter oAuth with .NET | Shannon Whitley. Se condividi, condividilo: Codice oAuth, twitter Using ASP.Net [...]
- Create Simple Twitter client with .Net « #Just Another Place To Stop By
[...] about handilng OAuth in .Net. There’re several library to do this one. I found a nice blog by Shannon Whitley with example how we dealing with OAuth in .Net. You can start from [...]
- 60+ .NET libraries every developer should know about. | Webdistortion
[...] Whitley offers this example: Code | Live [...]
- Twitter e a mudança para o oAuth « Soft Chill
[...] utilizar o código postado por Shannon Whitley com algumas correções sugeridas pelo Stephen [...]
- Twitter Authentication going to break.. |
[...] method (more info). That is bad news. I don’t know how to program or use that. There are .NET examples available. So it looks like we’ll have to stop using the WGET. Anyone? See the [...]
- Twitter oAuth with .NET | Shannon Whitley - Mustafa Kipergil - Mustafa Kipergil
[...] http://www.voiceoftech.com/swhitley/?p=681 June 30, 2011 at 07:00AM No Comments » Posted in Uncategorized [...]
- O.R. and social networking: Twitter, Solver Foundation and MIP « Nathan Brixius
[...] is called OAuth. Shannon Whitley wrote a nice OAuth package for .Net and posted it on his blog here. Go grab that and put it in your App_Code directory. I changed the namespace to [...]
- O.R. and social networking: A Solver Foundation MIP model to suggest Twitter followers « Nathan Brixius
[...] is called OAuth. Shannon Whitley wrote a nice OAuth package for .Net and posted it on his blog here. Go grab that and put it in your App_Code directory. I changed the namespace to [...]
- AuthPack Provides .NET oAuth for Twitter, Facebook, LinkedIn, and Google | Shannon Whitley
[...] I’ve published a project on GitHub that includes examples for authenticating users with some of the major social sites. LinkedIn and Twitter have very similar oAuth implementations so I was able to leverage all of my earlier Twitter .NET oAuth work. [...]
- Twitter Authentication going to break.. | Domoticaworld.com
[...] method (more info). That is bad news. I don’t know how to program or use that. There are .NET examples available. So it looks like we’ll have to stop using the WGET. Anyone? See the [...]
- Sign into SharePoint 2010 with Facebook using a custom STS | Microsoft Enterprise Technologies
[...] and will be integrated into our custom STS. It should be mentioned that this class is based on work done in 2009 by Shannon Whitley. Gotta give credit where credit is due. [...]
- (Twitter OAuth) How do you extract the user data from the xml and send it to a string?
[...] http://www.voiceoftech.com/swhitley/index.php/2009/03/twitter-oauth-with-net/ [...]
- Twitter api + OAuth 'random' 401 error | Question and answer
[...] the OAuth exemple code from http://www.voiceoftech.com/swhitley/index.php/2009/03/twitter-oauth-with-net/ [...]
- 60+ .NET libraries every developer should know about. - Dg3World
[...] Whitley offers this example: Code | Live [...]
- Coding the Tweet, Redux | Coding the Wheel
[...] code is still using Eran Sandler and Shannon Whitley’s oAuth/Twitter library but with additional changes to support the new PIN mechanism. If you have visions of .NET Twitter [...]
- Coding the Tweet: Building a Custom Branded Twitter Application | Coding the Wheel
[...] That’s really all there is to it. You now have a custom branded (if somewhat bare-bones) Twitter client which will tag each of your tweets with your URL of choice. The above code can easily be expanded to provide additional functionality or even turned into a full-fledged Twitter client. It can also be very easily converted to a web-based paradigm. [...]

@Paul Shriner – Been there myself. Just glad to hear it’s working.
Thanx a lot Shanon….I m beginner in Asp.net…I spent my whole 1 day for doing OAuth twit posting on twitter…Nobody on the internet gives a perfect solution….But finally I get perfect code..Once again thank u very much
Thanks for sharing this!
Such a help! Thank you.
[...] http://www.voiceoftech.com/swhitley/?p=681 June 30, 2011 at 07:00AM No Comments » Posted in Uncategorized [...]
Shannon,
Thanks for a great library. I have a quick question;
when I create an application on twitter dev portal, it generates Access Token and Access Token Secret.
When I set these value to your _token and _tokenSecret, I get permission denied.
Any ideas?
I got this working fine. However, no matter how many times a user approve the Access/Deny dialog; it shows up again the next time. I check the user’s permission on his/her Twiter account, they already give the permission for this application; however the Access/Deny comes back again and again.
@Tim Duff – That is under your control. Once Twitter delivers the token and token secret to you, store it in a database. The next time that the user visits your site, use the token and secret from your database. You can also change the signon page using the authenticate link instead of the authorize address: http://api.twitter.com/oauth/authenticate
[...] is called OAuth. Shannon Whitley wrote a nice OAuth package for .Net and posted it on his blog here. Go grab that and put it in your App_Code directory. I changed the namespace to [...]
[...] is called OAuth. Shannon Whitley wrote a nice OAuth package for .Net and posted it on his blog here. Go grab that and put it in your App_Code directory. I changed the namespace to [...]
Hi Shan,
string url = “”;
string xml = “”;
oAuthTwitter oAuth = new oAuthTwitter();
oAuth.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
oAuth.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
oAuth.Token = “306151605-cX3lg8XBL6FC8wAw2jRXBa0uCanY866LXZ5rfE3N”;
oAuth.TokenSecret = “jWxwy7vV786AQLTG2RU1yBu6cFWTYmj6ZfUqrZBEDA”;
//url = “http://twitter.com/account/verify_credentials.xml”;
//xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
//apiResponse.InnerHtml = Server.HtmlEncode(xml);
//POST Test
url = “http://twitter.com/statuses/update.xml”;
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, “status=” + oAuth.UrlEncode(“Hello trying to do.”));
//apiResponse.InnerHtml = Server.HtmlEncode(xml);
I am getting 403 error. I could post to twitter twice after that i am getting the above error. Any help would be appreciated.
Thanks for great post.
The remote server returned an error: (403) Forbidden.
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: (403) Forbidden.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[WebException: The remote server returned an error: (403) Forbidden.]
System.Net.HttpWebRequest.GetResponse() +5376061
oAuth.oAuthTwitter.WebResponseGet(HttpWebRequest webRequest) in D:\BlissCity\BlissCity\BLL\oAuthTwitter.cs:273
oAuth.oAuthTwitter.WebRequest(Method method, String url, String postData) in D:\BlissCity\BlissCity\BLL\oAuthTwitter.cs:244
oAuth.oAuthTwitter.oAuthWebRequest(Method method, String url, String postData) in D:\BlissCity\BlissCity\BLL\oAuthTwitter.cs:199
BlissCity.SignInTweet.Page_Load(Object sender, EventArgs e) in D:\BlissCity\BlissCity\SignInTweet.aspx.cs:31
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Great work. We did a project based your example, works perfect. Then the last couple weeks the stored tokens are no longer working even tho the code has not changed. Are time is synchronized and thing look good when we redirect via the call back URL. Anyone else had a similar problem?
Thanks a million for this.
Could you please write a post on how to use Connect with Facebook along with twitter authentication. and how to manage them in my database that which user is associated with how many services… etc…
Hello, I downloaded your codebase onto my dev environment (VS2008). I copied my two keys into the web.config. checked to make sure the time on mymachine was correct and the started debug. My app has read/write access.
I got 401 UnAuthorized.
this is the call Stack:
oAuthSample.DLL!oAuthExample.oAuthTwitter.WebResponseGet(System.Net.HttpWebRequest webRequest = {System.Net.HttpWebRequest}) Line 272 C#
oAuthSample.DLL!oAuthExample.oAuthTwitter.WebRequest(oAuthExample.oAuthTwitter.Method method = GET, string url = “http://twitter.com/oauth/request_token?oauth_callback=http%3A%2F%2Flocalhost%3A4242&oauth_consumer_key={ consumer key removed}&oauth_nonce=9626540&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1314571939&oauth_version=1.0&oauth_signature=JHeJa17jeT8Rcr6DnREsIxB5XVw%3D”, string postData = “”) Line 244 + 0xb bytes C#
oAuthSample.DLL!oAuthExample.oAuthTwitter.oAuthWebRequest(oAuthExample.oAuthTwitter.Method method = GET, string url = “http://twitter.com/oauth/request_token”, string postData = “”) Line 199 + 0x3d bytes C#
oAuthSample.DLL!oAuthExample.oAuthTwitter.AuthorizationLinkGet() Line 71 + 0×16 bytes C#
oAuthSample.DLL!oAuthExample._Default.Page_Load(object sender = {ASP.default_aspx}, System.EventArgs e = {System.EventArgs}) Line 54 + 0×18 bytes C#
any ideas?
Thanks
N
perfect! thank you.
How do I save the Oauth information after a user has given my app permission to access their Twitter info?
I can’t seem to figure out how to call Twitter again without the user having to re-authorize my app.
Thanks
@Jay – Save the values of the User Token and User Token Secret to a database at the end of the authentication process. After that, you can create the AuthTwitter object again, load the token and tokensecret values from your database, and make a Twitter call without asking for the credentials again.
I just Downloaded the full code, but I got 401 error below:
The remote server returned an error: (401) Unauthorized.
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: (401) Unauthorized.
Source Error:
Line 271: finally
Line 272: {
Line 273: webRequest.GetResponse().GetResponseStream().Close();
Line 274: responseReader.Close();
Line 275: responseReader = null;
Source File: C:\Users\ahe\Downloads\sample\oAuthTwitter.cs Line: 273
Stack Trace:
[WebException: The remote server returned an error: (401) Unauthorized.]
System.Net.HttpWebRequest.GetResponse() +6111075
oAuthExample.oAuthTwitter.WebResponseGet(HttpWebRequest webRequest) in C:\Users\ahe\Downloads\sample\oAuthTwitter.cs:273
oAuthExample.oAuthTwitter.WebRequest(Method method, String url, String postData) in C:\Users\ahe\Downloads\sample\oAuthTwitter.cs:244
oAuthExample.oAuthTwitter.oAuthWebRequest(Method method, String url, String postData) in C:\Users\ahe\Downloads\sample\oAuthTwitter.cs:199
oAuthExample.oAuthTwitter.AuthorizationLinkGet() in C:\Users\ahe\Downloads\sample\oAuthTwitter.cs:71
oAuthExample._Default.Page_Load(Object sender, EventArgs e) in C:\Users\ahe\Downloads\sample\Default.aspx.cs:54
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Can anyone help me?
guys,
to avoid 401 Unauthorized error, make sure the Callback URL field in your app setting at dev.twitter.com is not blank.
even if you are setting the callback from the code, just put something there on the website.
http://twitpic.com/7h09go
[...] I’ve published a project on GitHub that includes examples for authenticating users with some of the major social sites. LinkedIn and Twitter have very similar oAuth implementations so I was able to leverage all of my earlier Twitter .NET oAuth work. [...]
If you experience the 401 error, make sure your app has Read and Write access in the Twitter developers website (https://dev.twitter.com/apps).
If you change the access permissions you need to recreate your access token.
Shannon:- I have used the application. But the Twitter icon (.png) is not showing in the Window. I am unable to fins the reason.
@Nishant – The links in the images assumed that the application was running at the website root. I removed the slashes in the new code.
[...] method (more info). That is bad news. I don’t know how to program or use that. There are .NET examples available. So it looks like we’ll have to stop using the WGET. Anyone? See the [...]
Good example, but I think it is on Oauth first version.
Do you know where I can find an appropriate code to Oauth 2 to .NET framework?
Thank you.
@Giampiero – Thanks. This is specific to Twitter and they don’t support oAuth 2.0 yet, so I haven’t looked into updating for 2.0.
Hi,
The below code marks an error for me.
“The name ‘apiResponse’ does not exist in the current context”
apiResponse.InnerHtml = Server.HtmlEncode(xml);
@David Reyes – apiResponse is just a textbox on the page that is used to display the output. If you don’t have a textbox with the name apiResponse, you can create it or simply view the results of “xml” in the debugger.
[...] and will be integrated into our custom STS. It should be mentioned that this class is based on work done in 2009 by Shannon Whitley. Gotta give credit where credit is due. [...]
[...] http://www.voiceoftech.com/swhitley/index.php/2009/03/twitter-oauth-with-net/ [...]
[...] the OAuth exemple code from http://www.voiceoftech.com/swhitley/index.php/2009/03/twitter-oauth-with-net/ [...]
Hello sir,
Just want to thank you up for the code and updates. After developing some applications with Twitter and FB using your code[a year ago], i was not in touch with oauth related development.
Your updated code is even more beneficial.
Today, I tried your code for Etsy and with some minor changes, it works like charm.
Thank you very much again.
Rocker
Thanks for the comment. You’re welcome.
Hi shannon i worked with the sample code provided by you.But now i was getting 401 aunthorized error while login only. i could able to post message using your code but while login i was getting this error. i have created new consumer key and consumer secret but still i could not able to get the twitter login screen . please help me on this.
[...] Whitley offers this example: Code | Live [...]
[...] code is still using Eran Sandler and Shannon Whitley’s oAuth/Twitter library but with additional changes to support the new PIN mechanism. If you have visions of .NET Twitter [...]
[...] That’s really all there is to it. You now have a custom branded (if somewhat bare-bones) Twitter client which will tag each of your tweets with your URL of choice. The above code can easily be expanded to provide additional functionality or even turned into a full-fledged Twitter client. It can also be very easily converted to a web-based paradigm. [...]
Pretty nice post. I just stumbled upon your blog and
wished to say that I’ve really enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!