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-text=”Twitter oAuth with .NET (Shannon Whitley)”
data-count=”vertical”
>Tweet
192 Responses to “Twitter oAuth with .NET”
Leave a Reply
48 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 [...]

@Shannon Whitley
Other than the clock sync suggestion , I am already using the urlEncode and as we are just 2-3 friends who are using it, i don’t think we hit the API rate limit.I have gone through the specs for rate limit and right now it is far more than our usage.
One thing i would like to ask you is this that
Is there any difference in the following urls
http://api.twitter.com/statuses/update.xml
http://twitter.com/statuses/update.xml
Alas, it didn’t run for me.
{“Value cannot be null.\r\nParameter name: consumerKey”}
Hello Mr. Whitley,
I have posted a reply a couple of days ago but it isn’t there now.
Anyways will you please tell me whats the difference when i use
http://api.twitter.com/version/statuses/update.format
and
http://twitter.com/version/statuses/update.format
@Matt,
I guess you just forget to mention the Consumer key values in your configuration file.Take a look at that.
Hope it helps.
I am relatively unfamiliar with oAuth and am in the process of converting our Beema interface from Basic to oAuth. The GETS all work fine, but none of the POSTS operate correctly.
As an example,
FOR POST THE SYSTEM GETS:
url = http://twitter.com/statuses/update.xml
postData = oauth_callback=oob&oauth_consumer_key=h5k46JPoK3qFwHqzt67zNg&oauth_nonce=9245993&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1284425414&oauth_token=51595215-rA0emLOtrCN4AfbmUUZzpkjtJVBDVy1YoZQkS9dRK&oauth_verifier=QF9dzuAz2APmsEWuYvnU1UZvjbpepbjlU8ikw9J9oQ&oauth_version=1.0&status=Hello%20%40swhitley%20%2013%20Testing%20the%20.NET%20oAuth%20API&oauth_signature=Dkzapp8dUpCU%2ffwL%2bX%2fHmcvQ3cA%3d
WHEN I EXECUTE THIS LINE (263 – WebResponseGet Routine): responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
I GET THE ERROR: The remote server returned an error: (401) Unauthorized.
Any help would be greatly appreciated. Also, thanks for the basic blog which has saved me tons of time and is very much appreciated.
Peter Olson
Jonny was here
Hi Shannon Whitley,
The source code provided by you is very useful one.
can you help me out with a source for twitter profile image upload using OAuth authentication.
Thanks,
S.Thangavel
@Thangavel – I have some code to update the Twitter background that would probably work for profile images. I’ll put something together and create a new post.
@Beema Follow – Seems like a few people are having update issues. I don’t use that method very often so I haven’t tried it lately. Aside from what’s already here, I don’t have any other suggestions. I’ll try the code to make sure that it’s still working. I know I have seen some recent updates from other people who are posting updates successfully.
Am I right in saying this code example can no longer be used because of the changes to the Twitter API?
All I’m getting is a 401 error
hello Shannon,
I keep on getting a 401 Unauthorized error for the following:
let url = “http://api.twitter.com/1/users/lookup.json?screen_name=twitterapi,twitter”
oauth.oAuthWebRequest(oAuthTwitter.Method.GET, url, “?screen_name=twitterapi,twitter”)
while this work fine with one id:
let url = “http://api.twitter.com/1/users/lookup.json?screen_name=twitterapi”
oauth.oAuthWebRequest(oAuthTwitter.Method.GET, url, “?screen_name=twitterapi”)
Thanks a lot for this post
Acutally all good, the method only works in POST and my app was not Read&Write
Hey @Curt. Are you having the same problem that @Joachim had? Make sure your app setup at Twitter.com allows read/write if you’re trying to perform a status update.
Try out this link:
With OAuth: http://dotnetguts.blogspot.com/2010/05/tweet-posting-from-aspnet-using-oauth.html
Without OAuth: http://dotnetguts.blogspot.com/2009/04/twitter-posting-from-aspnet-website.html
Very Nice article but this class has some signing problems when using POST Methods.
Do you have an updated code?
Thanks
Ricardo
@Ricardo – The current code should be fine. Make sure you’re using the oAuth.UrlEncode method to encode the variables (not HttpUtility or Server).
Twitter Comment
Twitter oAuth with .NET (Shannon Whitley) [link to post]
– Posted using Chat Catcher
[...] Twitter oAuth with .NET | Shannon Whitley. Se condividi, condividilo: Codice oAuth, twitter Using ASP.Net [...]
Nice code! very concise. One question. Twitter has the capability to bypass the authorization screen if you are posted to one account. They give you an oauth_token and a oauth_token_secret. You should be able then to post directly to the twitter account but you still need the oauth_verifier. Any ideas on how to get that without resorting to the Twitter auth screen round trip?
Hi @pat,
Are you referring to the cookie login? I’ve seen that with the PHP oAuth library. I haven’t implemented that or looked to see how that’s done.
thank u shannon.when i m testing in local i got an error’The remote server returned an error: (401) Unauthorized.’ in this line
url = “http://twitter.com/account/verify_credentials.xml”
It looks like you may not be using the correct token and secret. Check the comments for other responses to 401 errors.
After getting Access Token,when executing the line,
string json = twitter.WebRequest(oAuthTwitter.Method.GET, “http://twitter.com/account/verify_credentials.xml”, string.Empty) i got an error in oAuthTwitter.cs WebRequest method in this line:
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
The error is: ’The remote server returned an error: (401) Unauthorized.’
Thanks in advance.
sorry
i m calling webrequest method instead of oauthwebrequest method.now its working fine.thank u all
Hi Shannon, thanks for this post.
I’m just wondering… this post is about using the oauth lib to access twitter api and post etc…
but then i noticed that in this site you use the javascript based @anywhere Tweetbox to post tweets.
So after looking at both methods it looks like the @anywhere Tweetbox is more user-friendly – with the nice-looking twitter popup with ‘connect/cancel’ buttons (as apposed to full-page deny/allow one generated from code)
The problem is that i’m not sure how to access the tweets after they have been sent through the @anywhere twitter box.
I’m sure this is possible since I see that you have implemented this on your website.
So how can you display posts that are sent using the @anywhere twiiter box.
Thanks again.
There is incorrect UrlEncode() method in OAuthBase class. It did not work with characters with accents. It throws “(401) Unauthorized” error.
This is working version:
protected string UrlEncode(string value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
string res = HttpUtility.UrlEncode(symbol.ToString());
if (res.IndexOf(‘%’) != -1)
{
result.Append(res.ToUpperInvariant());
} else {
result.Append((res == “+”) ? “%20″ : res);
}
}
return result.ToString();
}
I am trying the same code to poast tweets for 5 test users.The program runs good for first few tweets but after that i get the error 403 Forbidden.althoug i am post different message at every time.Can any one of you please help me.
Thanks,
D
Your code (and the original) suffer from the same problem – they don’t handle special character encoding for parameters. This caught us out too!
As mentioned, paramater encoding requires special attention with double encoding of special characters that are used in standard URI specification – the OAuth URI specification is different. The OAuth guidelines can be found in RFC5849 section-3.4.1.1 & also RFC3986 section 2.4
For those who want to see an example with process and data, here’s a live Sample demonstrating the OAuth 1.0a Authentication process (requires an active account with http://www.etsy.com):
http://www.tools4etsy.com/developer/etsy-v2-api/samples/OAuth/default.aspx
For POST & PUT methods, there’s more to the specification than the class offers in this article that can be found in the RFCs mentioned above.
G.
Hello Mr. Whitley,
Finally i have developed a small application with the help of your blog. All credit goes to you. Thanks for that. Initially everything was working fine
But just two days ago,For some unknown reasons , my application stop working.It is working on my local system but not other systems. I have cross checked all the dll & codes.It is all the same but it gives 401 error only on other system.It doesnt even show the twitter login page on other system..It is still running fine on my local system. Please guide me as what could be the possible cause and its solution.
here is the stack trace to explain further :
System.Net.HttpWebRequest.GetResponse() TwitterAuthentication.oAuthTwitter.WebResponseGet(HttpWebRequest webRequest) TwitterAuthentication.oAuthTwitter.WebRequest(Method method, String url, String postData) TwitterAuthentication.oAuthTwitter.oAuthWebRequest(Method method, String url, String postData) TwitterAuthentication.oAuthTwitter.AuthorizationLinkGet()
Thanks
Shadab
@Mr. Whitley,
thank you so much for sharing this code.
I had to change ‘UrlEncode’ method in the ‘OAuthBase’ class. the new implementation of method is given below. I changed this method because I was unable to post special characters to twitter when updating status.
public string UrlEncode(string value)
{
return Uri.EscapeDataString(value);
}
I am getting a compile time error The name “apiResponse does not exist in the current context”, and would appreciate any help. (I’m new at this).
Here is the relevant code snippet:
{
//Get the access token and secret.
oAuth.AccessTokenGet(System.Web.HttpContext.Current.Request["oauth_token"], System.Web.HttpContext.Current.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 = System.Web.HttpContext.Current.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);
}
}
Thank you!
We want to retrieve a Twitter user’s email id as part of the authentication process or through one of the API calls. The APIs seem to cover almost everything except email id retrieval.
Please let me know if anyone knows how to retrieve it programatically. I am using .net amd javascript in our application.
@Harish – Twitter doesn’t expose the e-mail address. You won’t be able to retrieve it.
@Magicmike “apiResponse” is just the id of a textbox on the webform to display the response text. Add a textbox to the webform and name it apiResponse. It should already exist in the sample code.
Hi,
I need your help.
I want to send a custom message (for ex “Happy New Year”) to twitter. I need to send this message from my asp.net web service.
Kindly help me on the below points….
1. Which is the application type (client/browser) I need to select while registering my application?
2. I can not give any callback URL since my web service not hosted in online
3. Also, I need to send the twitter username and password through programming for authentication since there is no user interaction in my web service.
Since I’m new to twitter and twitter API, kindly guide me and please provide you inputs/thoughts
Thanks a lot in advance.
Regards
Gopi.R
Hello Mr. Whitley,
We have a problem which i think you could help us on.
“Is there any possible way with the help of which we can identify and get the information of user logged into http://www.twitter.com on our site.”
Thanks
Rockers
Hi @Rocker – When visiting your site, you want to determine if the visitor is logged into Twitter and then retrieve their Twitter information? Is that correct?
Yes Sir.
@Rocker – I think there should be a login button or form. You wouldn’t want to try to grab information from people if they aren’t actively providing it.
[...] 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 [...]
Very good article. Thanks. If I set the callback url to something different to oob I get error 401. Could you help me out to figure out what’s wrong with my approach?
I registered my web site on twitter and the callback url belongs to this site.
Hello Mr. Whitley,
Using the current code, i am able to update the status on twitter.
But the problem is when i pass a parameter “in_reply_to_status_id” in the Request to update the status, it doesn’t seems to work.
Even though status has been updated and no error is generated,the response that is returned doesn’t contain any value in in_reply_to_status_id node.
Basically,we want to achieve the reply functionality of the twitter for a tweet.
Thanks
Rockers
@Rocker – Sorry, I haven’t tried using in_reply_to_status_id. There could very well be a bug with the API. I’d suggest asking about it in the Twitter developer forum.
@Claudio – Thanks. You can send me an e-mail and I’ll try to help.
[...] Whitley offers this example: Code | Live [...]
[...] utilizar o código postado por Shannon Whitley com algumas correções sugeridas pelo Stephen [...]
Hi Shannon,
I have seen the earlier comment on the status not working.
I have this code in my web service, hence i pass the variables in an entirely different method than it is for login.
var oAuth = new oAuthTwitter();
oAuth.Token = token;
oAuth.TokenSecret = secret;
oAuth.OAuthVerifier = verifier;
oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, “http://twitter.com/statuses/update.xml”, oAuth.UrlEncode(“hello”));
It doesn’t work and I receive a 403 error, I even tried not giving oauthverifier but still no luck.
Appreciate if you could help.
Thanks,
Arun.
Hi Shannon,
In the above code sample I am trying to tweet without necessarily logging in again and again.
Once logged in I am caching those values and trying to tweet based on them.
Is it possible at all – please let me know if you get a chance.
Arun.
Your code is correct except for the OAuthVerifier. Only specify the OAuthVerifier during the oAuth login process. You never use it with Twitter methods.
[...] 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 [...]
I don’t understand the purpose of the “OAuthVerifier” can you explain to me, which value we insert ???!
Sorry for my english, i’m french.
Hi @Julien,
I don’t really either.
I include it as part of the authentication process when using an oauth callback, but it is never used in any other calls. That’s the main point that confuses people. The oauth verifier should only be used during the authorization call. Never use it when calling any other Twitter methods.
You know I have been struggling with why I get the 401 error after I have successfully logged in and call a method with the correct tokens. SUPER FRUSTRATING!
First time though I save the tokens to the Database:
oAuth.AccessTokenGet(Request["oauth_token"].ToString(), Request["oauth_verifier"].ToString());
sm.SaveOAuthCredentials(
Convert.ToInt32(application_provider_id),
oAuth.Token,
oAuth.TokenSecret);
Where application_provider_id is an PK of the logged in user.
—–
Hence fourth we are using this code:
oAuth.Token = oauth_token;
oAuth.TokenSecret = oauth_secret;
var url = “http://twitter.com/account/verify_credentials.xml”;
var xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
Response.Write(Server.HtmlEncode(xml));
—-
What am I missing?
It is always a little while after you post that you reaize that there was a typo in the sproc and the retrieval!!!
Arg!
Thanks and great lib!
Paul