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




swhitley (Shannon Whitley) said,
Wrote on March 19, 2009 @ 4:27 pm
Twitter Comment
Twitter oAuth with .NET example code [New Post] – [link to post]
– Posted using Chat Catcher
akvalley (Anthony K. Valley) said,
Wrote on March 19, 2009 @ 4:35 pm
Twitter Comment
@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 ©) said,
Wrote on March 19, 2009 @ 7:02 pm
FriendFeed Comment
Twi… [link to post]
– Posted using Chat Catcher
cavalierandy (Randy Dillon) said,
Wrote on March 24, 2009 @ 6:46 pm
Twitter Comment
Twitter oAuth with .NET [via FAQ] [link to post]
– Posted using Chat Catcher
send2moran (send2moran) said,
Wrote on March 25, 2009 @ 10:37 pm
Twitter Comment
@gromer, try this class – [link to post] the important line is : oAuth.AccessTokenGet(Request["oauth_token"]);
– Posted using Chat Catcher
moomerman (Richard Taylor) said,
Wrote on March 26, 2009 @ 4:56 am
Twitter Comment
@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) said,
Wrote on April 6, 2009 @ 10:07 am
Twitter Comment
working on an oAuth setup for .net and twitter, this helps [link to post]
– Posted using Chat Catcher
zerophyte (Cian H) said,
Wrote on April 6, 2009 @ 5:20 pm
Twitter Comment
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
Dan Swatik said,
Wrote on April 18, 2009 @ 10:55 am
This isn’t the whole code where is the oAuthTwitter class?
Mob Dub said,
Wrote on April 20, 2009 @ 1:40 am
test from voice of tech
earljon said,
Wrote on April 27, 2009 @ 8:25 am
Thanks @Shannon! Very useful as a starting point for my twitter library!
nicely done!
Tommy Kolkman said,
Wrote on April 28, 2009 @ 2:57 am
Thanks @ Shannon for the tutorial.
I can’t seem to get it right though – i’ve got a test web site running at http://www.dcevent.mobi, and the application will connect with twitter here, it supplies the consumer key and callback, but the callback won’t fire!
Plus, upon refreshing dcevent.mobi, the access token doesn’t seem to be there, ’cause it’s firing an authorization request again. Any of you guys know what’s going on here?
earljon said,
Wrote on April 28, 2009 @ 8:12 am
@Tommy Kolkman
just make sure your twitter application is set as Web/Browser as your application type for you to catch/specify valid callback that will be called by twitter.
Sean said,
Wrote on May 12, 2009 @ 3:25 pm
ok, so I’m able to retrieve and reuse the Token and TokenSecret. I have one additional problem. When Twitter calls back to the page where Request["oauth_token"] != null, there is no session data available.
How can I link the tokens to the active user’s session for future reuse?
Steve Holstad said,
Wrote on May 14, 2009 @ 7:23 am
Great work, thanks for providing this Shannon!
SteveHolstad (Steve Holstad) said,
Wrote on May 14, 2009 @ 7:43 am
Twitter Comment
Excellent .NET Twitter oAuth class by @swhitley [link to post] Community dev at it’s best.
– Posted using Chat Catcher
Shannon Whitley said,
Wrote on May 16, 2009 @ 10:33 pm
I think I already provided this info. to Sean, but I’ll include it here for anyone else:
Twitter had to remove the oauth_callback variable, but I’m still sending information in it and then checking the referrer on the call back from Twitter. It’s a hack, but it seems to be working until Twitter can provide an alternative.
Saar Paamoni said,
Wrote on May 18, 2009 @ 2:39 pm
Thanks for providing this solution, I am getting error: Could not load type ‘oAuthExample._Default’.
any thoughts?
luis_batista said,
Wrote on May 19, 2009 @ 7:46 am
Saar Paamoni,
If you use VS2005, need create a New -> Project –> ASP.NET Web Application.
VS2005 create a project with a namespace. You need rename it to “oAuthExample”, past code from “Default.aspx” (in example) and add .cs files to project.
Build.
You need register you webapp in Twitter (http:// twitter.com / oauth_clients) to use Twitter OAuth.
One problem, Twitter don’t permit localhost (and 127.0.0.1) callback’s, you need a website online to test the example.
Regards,
LB
Saar Paamoni said,
Wrote on May 19, 2009 @ 2:26 pm
Ok, I figured it out something was off with the namespace…
luis thanks for the heads up on registering and localhost, I have now a page that can signin with twitter.
New problem: When I try to post (using the commented lines in the example i get “The remote server returned an error: (401) Unauthorized.” ideas?
Mickey Binder said,
Wrote on May 22, 2009 @ 11:43 am
@Saar
Did you create a proper signature before posting?
Here is how I generate a signatured status update and that works (Besides sometimes with special characters)
string message = _CtlMessage.Text;
Uri uri = new Uri(String.Format(“http://twitter.com/statuses/update.xml?status={0}”, message));
string sigUrl = “”;
string sigParameters = “”;
string signature = oAuth.GenerateSignature(uri, oAuth.ConsumerKey, oAuth.ConsumerSecret, kvidrUser.Token, kvidrUser.TokenSecret, “POST”,
oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out sigUrl, out sigParameters);
string xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, sigUrl, sigParameters);
Nick said,
Wrote on May 25, 2009 @ 10:19 pm
It would be awesome if someone could ever have a VB.Net version of code…. or if their C# code could actually be converted successfully through an online converter. Oh well, the search continues.
Ramasubramanian Mahadevan said,
Wrote on May 25, 2009 @ 11:51 pm
first off, thanks to Shannon and all the contributors for a wonderful thread!
For our website, we wanted to check whether we can 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.
To avoid ethics breaches, we need the email id, and wondered if anyone here has obtained them programmatically (we use .Net and Javascript).
Thanks once again,
ramsub
Cool app! said,
Wrote on June 10, 2009 @ 2:15 pm
Thanks! This is a great example and very useful. I am a bit puzzled and could use an explanation: what if I want my end user to only have to authenticate with twitter once. Kind of like the SSO experience between bighugelabs.com and flickr. http://bighugelabs.com/flickr/flickr-auth.php
Is this usage of OAuth orthogonal to that kind of SSO experience?
It seems ever time I run this sample application to tweet pro grammatically, it asks the user to authenticate.
What am I missing?
Thanks!
Shannon Whitley said,
Wrote on June 10, 2009 @ 4:56 pm
Thanks for all the great comments.
@Cool, you can save the token and token secret for later use. Skip over the first part of the code and simply set the object’s token and token secret from the saved credentials.
Haroon Sarwar said,
Wrote on June 11, 2009 @ 3:47 am
Thanks for this, it really helped me a lot…
If anyone is wanting to use oauth_callback parameter, you will need to make some changes to the code so that it conforms to the OAuth 1.0a specification (see http://groups.google.com/group/twitter-development-talk/browse_frm/thread/472500cfe9e7cdb9#)...
I made some changes and got it to work successfully…if anyone wants to have a look I’ve uploaded here: http://haroon84.googlepages.com/Twitter-1.0a.zip
buster brown said,
Wrote on June 13, 2009 @ 10:51 am
Hi Shannon,
Thank you for posting this code snippet. However, I have been trying for the last week to get it to work without any success.
I have the authorization link set correctly. I then provide my Twitter credentials and when Twitter redirects to my Callback page, I receive an error that says: “A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 64.202.165.130:3128″
In addition, the application does not show up in my “connections” tab within Twitter. Which would imply that the user never gets authorized with the application. I suspect this has to do with a failure in recieving my access token.
Do you have any recommendations? This is really frustrating. Thank you for your efforts.
swhitley said,
Wrote on June 13, 2009 @ 9:45 pm
@buster brown:
When you say, “I have the authorization link set correctly” — do you see the correct oAuth login page for Twitter? It should identify you or your application when it is asking you to allow or deny access. That’s the only requirement to add it to your “connections” tab. I want to understand that part first since you should definitely see the application in your connections if you’ve approved it.
Haroon said,
Wrote on June 15, 2009 @ 8:51 pm
in oAuthTwitter.cs I think there is a small bug:
public string ConsumerSecret
{
get {
if (_consumerSecret.Length == 0)
{
_consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
}
return _consumerSecret;
}
set { _tokenSecret = value; }
}
The set part should be: set { _consumerSecret = value; }
Steve Crane said,
Wrote on June 16, 2009 @ 12:26 am
This is intereting
Darren said,
Wrote on June 16, 2009 @ 6:54 am
has anyone managed to get this to work with the login with twitter method?
I have it working in the old way but can’t see away to do the login without rewriting it.
Any pointers I have missed would be great
thanks
Saar Paamoni said,
Wrote on June 16, 2009 @ 7:55 pm
maybe it’s obvious to everyone but me but since i spent way too much time getting 401 trying to post to twitter, here goes…
I wanted to save the Token and TokenSecret for future use by the user in some other page in the site, what i didn’t realize is that the oauth_token on the callback isn’t the actual token, you have to call:
oAuth.AccessTokenGet(Request["oauth_token"]);
and then save the oAuth.Token
Thanks for the heads up send2moran
Shannon Whitley said,
Wrote on June 17, 2009 @ 1:59 pm
Thanks, @Haroon! — I’ve fixed the code.
Tseelee said,
Wrote on June 19, 2009 @ 1:58 am
Hi guys,
Is anyone ever tried to use this code in C# WPF application?
I guess I have to change the line:
oAuth.AccessTokenGet(Request["oauth_token"]);
Request["oauth_token"]?
Tse
Craig said,
Wrote on June 25, 2009 @ 8:58 pm
I’ve used Shannon’s oAuth implemetation with my own .Net program. I’ve been able to save the token and the token secret and use them continually for the same user.
If you write a cookie to the client and if the twitter callback is to the same domain you should be able to identify the user that made the request.
That said a better way is to use the new oAuth callback method since it will work across multiple domains.
oAuth is still in the early stages and I’ve had a lot of headaches with it but it appears to be getting a lot of adoption so it’s not a bad thing to learn.
Twitter OAuth in C# | Die In A Hole said,
Wrote on June 27, 2009 @ 1:34 pm
[...] 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 [...]
Duane Roelands said,
Wrote on June 29, 2009 @ 4:18 am
Has anyone had any success using this library for a desktop application and the “PIN” mathod for OAuth? I’m having a devil of a time. I can get the authorization link fine and Twitter gives me a PIN, but i can’t seem to get it passed back to Twitter for the final atep.
Chris McDonnell said,
Wrote on July 2, 2009 @ 4:19 am
Can someone tell me how I can make subsequent requests to the Twitter API using this code? It works fine for the initial authentication but after a refresh I get a 401 error.
I know I am supposed to supply the token and token secret to Twitter but I don’t know how to get them from the oAuth.AccessTokenGet(Request(“oauth_token”)) bit.
Thanks.
Brad said,
Wrote on July 3, 2009 @ 8:38 pm
Hi guys:
VB developer, working with a version of the code that I converted from these c# examples. I’ve read through the oAuth documentation, and stepped through the code, but I still return 401 (unauthorized) errors before ever making it to the Twitter page that allows access. It bonks white trying to get a request_token. I’ve registered my app, and have a legit consumer key and secret. Any ideas what on to try next?
Thanks for any help you can provide.
Brad
Brad said,
Wrote on July 5, 2009 @ 12:11 pm
** Follow-up ** I built Shannon’s C# project and my converted VB project and stepped through each of them simultaneously, keeping two watch windows open so I could compare the two. It turns out that the conversion library I used didn’t implement the comparer class properly, so the query string parameters weren’t sorted correctly. Although I’m not sure if the order of the query parameters matters (does it affect the hash?).
It was also appending an extra “&” symbol to the signature which invalidated my request for a token. As my daughter says, “all done”.
Interestingly, I’ve encountered the same issues with other VB conversions I have found, including one posted on the oauth.net website.
rohit said,
Wrote on July 9, 2009 @ 7:33 am
Hi,
Can any body please help in providing the sample code of.Net of POST method.
I am using oAuth API class
Regards
Rohit
How to update on Twitter account from code? said,
Wrote on July 15, 2009 @ 6:28 am
[...] Was this link no use? Twitter oAuth with .NET | Shannon Whitley [...]
twitiki said,
Wrote on July 15, 2009 @ 1:38 pm
Great…thanks. I’ll check it out.
Jasper St. James said,
Wrote on July 16, 2009 @ 10:21 am
Thanks for the excellent sample! As the kids would say: 100% metal..
Jeff Brown said,
Wrote on July 17, 2009 @ 8:39 am
i downloaded the zip file today, set it up in iis to run and got this error.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type ‘oAuthExample._Default’.
Source Error:
Line 1:
Jeffbrown711 (Jeff Brown) said,
Wrote on July 17, 2009 @ 12:53 pm
Twitter Comment
@ardalis u have any working snipits of something like this? [link to post]
– Posted using Chat Catcher
Jeffbrown711 (Jeff Brown) said,
Wrote on July 17, 2009 @ 1:45 pm
Twitter Comment
@ardalis looking to authenticate via oauth – missing something that is not allowing this to run [link to post]
– Posted using Chat Catcher
ardalis (Steve Smith) said,
Wrote on July 17, 2009 @ 1:46 pm
Twitter Comment
@Jeffbrown711 you just want some code that talks to twitter’s API in C#, or what?
– Posted using Chat Catcher
Joseph M. Winett said,
Wrote on July 19, 2009 @ 2:25 pm
Shannon, thanks for the OAuth library stuff!
Dislay said,
Wrote on July 22, 2009 @ 5:51 pm
Hey everyone !!
I get to go through the all process of login, accessing stuff, and I got to display the statuses but, how can we then, post a status ?
Because right now, what it does is giving me the 401 error when I refresh the page…
My question is : Can we save the access token and then refresh the page as much as we want ?
Shannon Whitley said,
Wrote on July 23, 2009 @ 8:14 am
@Dislay – Yes, just save the user token and secret and use it on all calls. You don’t need to go through any of the other processes once you have the token and secret for the user.
Taing Dislay said,
Wrote on July 23, 2009 @ 9:48 am
I’m sorry but hehe, I don’t get it.
Because in the code, it is supposed to save the Token and Token Secret already when you get the access. And then when you call the oAuthWebRequest function, then it reused those variables but it still gives me the 401 error…
Taing Dislay said,
Wrote on July 23, 2009 @ 11:00 am
nevermind, I just used some input hidden fields to store the data
Mikey said,
Wrote on July 23, 2009 @ 7:47 pm
i got an error
Could not load type ‘oAuthExample._Default’.
Jeffbrown711 (Jeff Brown) said,
Wrote on July 28, 2009 @ 6:39 pm
Twitter Comment
@swhitley where is the latest working version of [link to post]
– i am unable; to get this to work. thks
– Posted using Chat Catcher
swhitley (Shannon Whitley) said,
Wrote on July 28, 2009 @ 7:42 pm
Twitter Comment
@Jeffbrown711 E-mail me and maybe I can help with specifics.
– Posted using Chat Catcher
swhitley (Shannon Whitley) said,
Wrote on July 28, 2009 @ 7:43 pm
Twitter Comment
@Jeffbrown711 I believe this code still works: http://voiceoftech.com/downloads/oauthtwitterexamplenet.zip
– Posted using Chat Catcher
Michael Dillon said,
Wrote on August 5, 2009 @ 9:12 pm
Plus one man, plus one. Now how about you walk us through sign in through twitter like you do with your comments.
mchid (mark chidlow) said,
Wrote on August 13, 2009 @ 9:18 am
Twitter Comment
oh the joys of oAuth .NET at [link to post]
– Posted using Chat Catcher
mariusdima (md) said,
Wrote on August 13, 2009 @ 9:31 am
Twitter Comment
Hei! Twitter oAuth with .NET [link to post]
– Posted using Chat Catcher
Puneet Sharma said,
Wrote on August 18, 2009 @ 12:01 am
Hi,
I am connecting to twitter through my application.
I want to look for Allow / Deny access (for posting on twitter) page only once, the first time when user is prompted for it.
Once he has done “Allow”, this wh must not again go to that page rather it must directly give me the Token when user next time does the same action, is there any way out for it.
Thanks in Advance.
Puneet
Viscus Nishant said,
Wrote on August 22, 2009 @ 12:30 am
Hi,
Anyone can please send me this sample code full version. I am trying to do the same but i required relogin to get my status updates in my asp.net web application.
Thanks in advance
Asha said,
Wrote on August 25, 2009 @ 1:49 am
Thanks for providing this solution, I am getting error: Could not load type ‘oAuthExample._Default’.
any thoughts?
Jeniffer said,
Wrote on August 25, 2009 @ 1:51 am
Could not load type ‘oAuthExample._Default’.
docblop (Mike Schaefer) said,
Wrote on August 30, 2009 @ 4:54 pm
Twitter Comment
@stuartmanning there’s an oauth implementation for .net already. no need to reinvent the wheel. [link to post]
– Posted using Chat Catcher
stuartmanning (Stuart Manning) said,
Wrote on August 30, 2009 @ 5:36 pm
Twitter Comment
@docblop and it is ‘often’ used in CodePlex.com OAUTH contribute projects
– Posted using Chat Catcher
stuartmanning (Stuart Manning) said,
Wrote on August 30, 2009 @ 5:37 pm
Twitter Comment
@docblop thanks =) there’s a ‘little’ more to do than just that example.. however it has ‘inspired’ alot of other to take this forward
– Posted using Chat Catcher
docblop (Mike Schaefer) said,
Wrote on August 30, 2009 @ 6:42 pm
Twitter Comment
@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
– Posted using Chat Catcher
stuartmanning (Stuart Manning) said,
Wrote on August 30, 2009 @ 7:44 pm
Twitter Comment
@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
– Posted using Chat Catcher
Oscar Peli said,
Wrote on August 31, 2009 @ 3:20 am
I used This library and it’s simple and useful but I have a little question:
How can I pass parameters to GET commands?
e.g. http://twitter.com/statuses/friends_timeline.rss?page=3
I cannot understand where to pass the “page=3″ parameter to the oAuthWebRequest(Method method, string url, string postData) method.
If I pass it in postData it is, obviously, ignored; if I pass together with the url, the private List GetQueryParameters(string parameters) method cut it out.
Thanks
navjot singh said,
Wrote on September 7, 2009 @ 2:22 am
I tried the above quote, its working fine till i am retrieving the profile of any user after the authentication. but moment i try to update status of any status (post tweet) it gives me below error
The remote server returned an error: (403) Forbidden.
i’ll be very thankful if someone can help me out for this.
prakash1979 (prakash) said,
Wrote on September 8, 2009 @ 3:29 am
Twitter Comment
[link to post] via @addthis
– Posted using Chat Catcher
chridam (Chris Dambamuromo) said,
Wrote on September 8, 2009 @ 4:33 am
Twitter Comment
Twitter oAuth with .NET [link to post] via @addthis
– Posted using Chat Catcher
jason said,
Wrote on September 8, 2009 @ 12:27 pm
Has anyone solved the issue that Chris McDonnell mentioned? I am getting that same issue. The first time I try something after getting the auth token it works…but then if I refresh or get the token from a session or cookie it fails.
pinky said,
Wrote on September 9, 2009 @ 2:52 am
I m getting error,
Value cannot be null.
Parameter name: consumerKey
what should I pass in consumer key?
swhitley said,
Wrote on September 9, 2009 @ 8:26 pm
@Oscar Peli – You should be able to pass the url along with the parameters as you normally would in the GET. Were you stepping through the code and maybe saw that the parameters were removed? The parameters are added back at a later point.
@pinky – The Consumer Key should be placed in your web.config file. Please look at the example code for the sample web.config.
ARIFUR RAHMAN said,
Wrote on September 12, 2009 @ 10:37 am
Hello, any one have any sample asp.net file which connect using the oauth and send after login to other page. I am not able to do this by this code.
Regard
ARIFUR RAHMAN
Siju said,
Wrote on September 15, 2009 @ 7:33 am
Hi,
Is there is anyway to get the email address of the user? I need to send a mail to the user which is obtaining from this.
Thanks,
Siju George,
swhitley said,
Wrote on September 15, 2009 @ 11:29 pm
@ Siju – The user must update his or her e-mail address through the profile page on your blog. That’s the only way to capture it.
ARIFUR RAHMAN said,
Wrote on September 16, 2009 @ 1:12 pm
Is there any one have working example of the asp.net twitter oauth login and post mess and get username.
Regard
ARIFUR RAHMAN
Jeff said,
Wrote on September 19, 2009 @ 10:44 am
@Taing Dislay Can you please provide some code on how you passed through the 401 error? This thing is making me crazy… I have no idea how to keep the credential once I refreshed my page…
Shannon Whitley said,
Wrote on September 21, 2009 @ 11:16 pm
@Jeff – Try storing your credentials in hidden fields on the page. That way they’ll persist between calls.
oAuth.Token and oAuth.TokenSecret should be saved.
You could use any method to persist the values (hidden input, cookies, Cache, database, session) — just save those values and you can reuse them for any other calls. Create a new oAuth object and assign the values from your stored variables.
Helen Neely said,
Wrote on September 27, 2009 @ 12:38 pm
Thanks for this piece of code, it has given me a very good head start on how to implement it in Java. I will post a comment once I’ve got it working.
Thanks again for sharing.
ahmd (ahmd) said,
Wrote on September 29, 2009 @ 7:09 am
Twitter Comment
[link to post]
– Posted using Chat Catcher
MichaelApproved (Michael Khalili) said,
Wrote on September 29, 2009 @ 10:15 pm
Twitter Comment
@BrandonWatson Recently setup OAuth with [link to post] and username/pass with Yedda http://bit.ly/10NPEI what you trying to do?
– Posted using Chat Catcher
Test Message | Hidden Treasures Of . Net said,
Wrote on October 4, 2009 @ 4:54 pm
[...] [...]
Santosh Kumar said,
Wrote on October 11, 2009 @ 2:46 am
Good
Tino S. said,
Wrote on October 11, 2009 @ 11:59 pm
Sorry to say this, but I think your URL-encoding method is broken für UTF-8 strings (which are expected, according to the twitter API).
I suggest using something like this:
public string UrlEncode(string value, Encoding encoding)
{
return System.Text.RegularExpressions.Regex.Replace(
HttpUtility.UrlEncode(value),
@”%[a-zA-Z0-9]{2}”,
m =>
{
char[] charArray = m.Value.ToCharArray();
if (char.IsLower(value[1])) charArray[1] = char.ToUpper(value[1]);
if (char.IsLower(value[2])) charArray[2] = char.ToUpper(value[2]);
return new string(charArray);
},
System.Text.RegularExpressions.RegexOptions.IgnoreCase
);
}
Some quick tests show this method returns the correctly encoded url, though I did not have the time to test it with the live twitter yet.
Hope it helps.
Tino S. said,
Wrote on October 12, 2009 @ 12:30 am
Let this be a lesson to you – never edit your code in a comment field
. Replace value[1] and value[2] with charArray[1] and charArray[2], respectively. Sorry for the mess.
Tino
Shannon Whitley said,
Wrote on October 12, 2009 @ 8:44 am
Thanks, Tino. That part of the code comes from the official oAuth library. We should address issues with it here and then I can update the sample:
http://code.google.com/p/oauth/
Tino S. said,
Wrote on October 12, 2009 @ 8:51 am
There seem to be more issues. I’ll try and check that, but I suspect that library returns the wrong signature for HTTP-POST messages containing special characters. I’ll post here if I found out more.
Malik said,
Wrote on October 12, 2009 @ 9:47 am
Really thanks,this code is very useful
Tino S. said,
Wrote on October 12, 2009 @ 9:49 am
…sorry for spamming your comments. I took the output of http://oauth.googlecode.com/svn/code/javascript/example/signature.html as reference for some quick unit tests. As it turned out, the signature will be correctly created, but the normalized parameter string is not, due to the problem I mentioned before. I implemented the method I posted above as an extension method – the tests ran just fine. I wrapped it all up in some classes and checked it in at http://code.google.com/p/twitover/source/browse/#svn/trunk. Help yourself, if you like.
(Yes, I’m writing a completeley unneeded c# twitter library. It’s just to get to know the API and have some fun beside work.)
jdmullin (J.D. Mullin) said,
Wrote on October 18, 2009 @ 11:42 am
Twitter Comment
@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]
– Posted using Chat Catcher
Lincy said,
Wrote on November 30, 2009 @ 3:12 am
I am just writing the same problem which i have mailed you.
I have used your code in my web application. But i am getting server error ‘/ ‘ application. The problem is that its not giving me the error details. It told me to add the tag and to set its mode in “off” state. I did the same but still its not showing me the error details.
The problem that i could tell you through my observance is that i am not getting into my url to insert the PIN number. Please help. Its urgent.
Lincy said,
Wrote on November 30, 2009 @ 3:19 am
my previous problem is missing some words. In the server error ‘/’ Application- run time error, its not showing me the error details. I added the tag with its mode in off state. Still its not showing me the details. Actually i am not getting redirected to my url to enter the pin number.Please help.
Shannon Whitley said,
Wrote on November 30, 2009 @ 8:06 am
Hi @Lincy,
It sounds like you need to create your web app directory:
http://msdn.microsoft.com/en-us/library/ha2y9493.aspx
lincy said,
Wrote on December 1, 2009 @ 6:49 am
I tried to create a web application directory.But i am not successful in that. I think my virtual directory path is not correct. What i did was i went into IIS mamnager> local computer> sites> add virtual directory. In that the path which i gave was the path where i created my web application. Is that correct? Hoping for an answer…
Sebastian Pereira said,
Wrote on December 2, 2009 @ 11:25 am
This example didn’t work for me.
I guess the callback doesn’t work with Localhost addresses. I tried to skip the callback and didn’t work either.
This method is too cumbersome! isn’t a better way to do so?
I guess I don’t get it yet the whole point of this.
lincy said,
Wrote on December 3, 2009 @ 7:01 am
I am not getting into my callback url but the oauth value and oauth verification value it is giving. on refreshing the page iam getting the server error-401 unauthorized.
Please help.
Shannon Whitley said,
Wrote on December 3, 2009 @ 12:41 pm
@Sebastian Right, the callback process changed. I haven’t taken the time to review the new process. I just point the return url on Twitter to “http://mytest.com” and setup mytest.com on my machine as 127.0.0.1 in my hosts file. Yes, it’s a little harder, but I think it’s better for the users.
@lincy
Make sure you save the token and token secret so you can reuse them. Refreshing the page will typically result in the token and token secret being lost because the oAuth object is local to the page load.
priya said,
Wrote on December 4, 2009 @ 2:46 am
I used your code in my application.I am not getting the token and the token secret value . Infact iam being directly send to the url for user authorization. Any suggestions?
Zain Shaikh said,
Wrote on December 13, 2009 @ 4:09 am
hey great article man, I have used your code in my application. its working great.
dixzan (Antonio Torres) said,
Wrote on December 13, 2009 @ 4:16 pm
Twitter Comment
@lhchavez estoy aprendiendo como registrar mi API para consumir todos los servicios de Twitter. Se llama oAuth. [link to post].
– Posted using Chat Catcher
lhchavez (lhchavez) said,
Wrote on December 13, 2009 @ 4:35 pm
Twitter Comment
@dixzan aaah el oAuth… tuvieron broncas de seguridad con eso cuando lo sacaron por primera vez
– Posted using Chat Catcher
Michael Khalili said,
Wrote on December 18, 2009 @ 6:45 am
Fix for UrlEncode. It uses the native urlencoder for special characters that produce int values > 2 digits.
public string UrlEncode(string value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if (unreservedChars.IndexOf(symbol) != -1)
{
result.Append(symbol);
}
else
{
//some symbols produce > 2 char values so the system urlencoder must be used to get the correct data
if (String.Format(“{0:X2}”, (int)symbol).Length > 3)
{
result.Append(HttpUtility.UrlEncode(value.Substring(value.IndexOf(symbol),1)).ToUpper());
}
else
{
result.Append(‘%’ + String.Format(“{0:X2}”, (int)symbol));
}
}
}
return result.ToString();
}
Testing Eatingbook said,
Wrote on December 21, 2009 @ 1:35 pm
hi
i have tried ur code, but it is not working for me. it opens a new window with:
Response.Redirect(oAuth.AuthorizationLinkGet() + “&oauth_callback=”);
but the new window is empty.
i have been researching for hours, please help!.
Testing Eatingbook said,
Wrote on December 21, 2009 @ 2:22 pm
urgh, sorry…found the error, totally my mistake.
working like a charm now
Shannon Whitley said,
Wrote on December 21, 2009 @ 2:36 pm
@Michael Khalili – Thanks for supplying the code. I’ll check it out and update my files.
@Testing Eatingbook – Just happy to hear it’s working for you.
Mike said,
Wrote on December 22, 2009 @ 5:47 pm
Thanks! Worked Great!
Andy said,
Wrote on December 24, 2009 @ 10:46 am
I’m setting getting the 401 error, even after saving the token + tokenSecret in session variables, any ideas?:
if (Request["oauth_token"] != null) Session["oauth_token"] = Request["oauth_token"];
if (Session["oauth_token"] != null)
{
oAuthTwitter oAuth = new oAuthTwitter();
if(Session["oauth_token_secret"] == null)
{
oAuth.AccessTokenGet(Session["oauth_token"].ToString());
Session["oauth_token_secret"] = oAuth.TokenSecret;
}
else
{
oAuth.Token = Session["oauth_token"].ToString();
oAuth.TokenSecret = Session["oauth_token_secret"].ToString();
}
string xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, “http://twitter.com/account/verify_credentials.xml”, string.Empty);
}
Thanks guys…
Andy said,
Wrote on December 24, 2009 @ 11:07 am
Read one of Saar’s posts and modified my code to the following:
oAuthTwitter oAuth = new oAuthTwitter();
if(Session["oauth_token_secret"] == null)
{
oAuth.AccessTokenGet(Session["oauth_token"].ToString());
Session["oauth_token_final"] = oAuth.Token;
Session["oauth_token_secret"] = oAuth.TokenSecret;
}
else
{
oAuth.Token = Session["oauth_token_final"].ToString();
oAuth.TokenSecret = Session["oauth_token_secret"].ToString();
}
Hope this helps someone else!
Thanks Saar!
Mike said,
Wrote on December 26, 2009 @ 4:25 pm
Just a heads up, the URLEncode Function causes a horrible death when the text is non UTF ( iso-2022-jp in my case ).
Ashish said,
Wrote on December 29, 2009 @ 6:48 am
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.
Response.Redirect(oAuth.AuthorizationLinkGet() + “&oauth_callback=your call back url”);
}
else
{
//Get the access token and secret.
oAuth.AccessTokenGet(Request["oauth_token"]);
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);
url = “http://twitter.com/statuses/update.xml”;
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, “status=” + HttpUtility.UrlEncode(“Ashish Testing…”));
apiResponse.InnerHtml = Server.HtmlEncode(xml);
}
}
}
hope that helps someone but easy to use…
in case of any problem mail me at ashish.oorja@gmail.com
nahyan said,
Wrote on January 5, 2010 @ 11:32 pm
hi Shannon Whitley,
gr8 work…can u help me to get twitsume api?is that available..
Vincent said,
Wrote on January 26, 2010 @ 1:06 am
Hey
Thanks for the article and code. Just one problem. I am getting a Access denied 401 error on the callback page.
This is the code I am using:
oAuthTwitter oAuth = new oAuthTwitter();
oAuth.AccessTokenGet(Request["oauth_token"]);
if (oAuth.TokenSecret.Length > 0)
{
//We now have the credentials, so make a call to the Twitter API. string url = “http://twitter.com/account/verify_credentials.xml”;
string xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, “”);
This line is giving the issue:
oAuth.AccessTokenGet(Request["oauth_token"]);
Any ideas what I am doing wrong?
jorge said,
Wrote on January 28, 2010 @ 6:03 pm
Hi, thks so mucho for the post, it was very useful for me.
A question, how do you get auto-close the popup window when I have signed on twitter and allowed your application and then get redirected as signed user in the main window of teh explorer?
GameTree » Blog Archive » Coding the Tweet, Redux said,
Wrote on February 15, 2010 @ 1:55 am
[...] 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 [...]
todd said,
Wrote on February 16, 2010 @ 12:51 am
Hello. Can someone provide a little more clarity on the 401 problem people are getting. I have things working fine on initial Page_Load but if I add a button that calls the following function from a button it fails? I think the problem is I don’t need to go thru oAuth again but not sure how to do it. Thanks.
protected void Button1_Click(object sender, EventArgs e)
{
string url = “”;
string xml = “”;
oAuthTwitter oAuth = new oAuthTwitter();
url = “http://twitter.com/statuses/update.xml”;
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, “status=” + oAuth.UrlEncode(“text”));
apiResponse.InnerHtml = Server.HtmlEncode(xml);
}
Thank you.
Shannon Whitley said,
Wrote on February 16, 2010 @ 8:45 am
oAuthTwitter oAuth = new oAuthTwitter();
oAuth.token = saved_token; //can’t recall actual prop name
oAuth.secret = saved_secret; //can’t recall actual prop name
You’ve created a new oAuth object, but you haven’t set the token and token secret. On your first call, you need to save the token and token secret and then reuse them in the Click event.
+60 librerias .net que todo desarrollador debería conocer « Hablando de web Desarrollo ágil de web en php, asp.net, javascript… said,
Wrote on February 17, 2010 @ 12:15 pm
[...] Whitley ofrece este ejemplo: Code | Live [...]
Twitter oAuth with .NET for the Desktop | Shannon Whitley said,
Wrote on February 18, 2010 @ 11:38 pm
[...] 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 [...]
Sourabh Sachdeva said,
Wrote on February 25, 2010 @ 12:55 am
can anyone tell what is consumer key. Is it twitter username or password or anything else. Actually i am new for twitter integration.
Thnx in advance.
Philip Tiju said,
Wrote on February 26, 2010 @ 12:58 am
gr8 stuff dude..
I need a small help…
I’m able 2 Authenticate and Tweet for the first time… Suppose If I try 2 tweet with the same token.. its shows Unauthorized … So I need to authenticate again.. plz let me know how to get rid off dat… I pretty new to OAuth… Plz gimme some valid example
Fabio Seixas said,
Wrote on February 28, 2010 @ 8:09 am
I translated both classes to VB.net.
The Basic oAuth VB.net class available in the oAuth.net does not work properly due to a bug in the oAuth parameters ordering function.
You can download the VB.net working version here: http://www.fabioseixas.com.br/files/oauth_twitter_dotnet_vb.zip
CC Tester said,
Wrote on March 5, 2010 @ 10:50 pm
Can’t get rid of the 401 error. Ugh.
Joel said,
Wrote on March 9, 2010 @ 6:14 pm
You have to save the token that is generated. Don’t save the token in the URL that comes from twitter. It’s not the same. After you call AccessTokenGet and oAuthWebRequest you can get the Token and Token secret from the object. Save this:
Session["Tweeted.TokenSecret"] = oAuth.TokenSecret;
Session["Tweeted.Token"] = oAuth.Token;
Stephen Denton said,
Wrote on March 10, 2010 @ 10:09 pm
My attempt at a bulletproof UrlEncode function for oAuth: http://blog.stephendenton.com/code/a-proper-urlencode-function-for-oauth-in-c-sharp/
Daniela said,
Wrote on March 16, 2010 @ 10:06 am
Erro 401
webRequest.GetResponse().GetResponseStream().Close();
????
Source File: (…)\App_Code\oAuthTwitter.cs
Line: 254
Daniela said,
Wrote on March 19, 2010 @ 11:44 pm
Finally everything worked properly! Even with the session. After much headache with the 401. Very Happy! (Sorry for the bad english )
Daniela said,
Wrote on March 19, 2010 @ 11:46 pm
I’m not sure, but I think the problem was because they had put the file in to a subfolder and was redirected to a file in the root!
robert h. said,
Wrote on March 26, 2010 @ 11:52 am
thanks for sharing man. learned a lot from your code.
Raj Aththanayake said,
Wrote on March 27, 2010 @ 6:48 pm
Awesome thanks a lot!!!
Remy Bakker said,
Wrote on March 31, 2010 @ 5:31 am
nice
Remy Bakker said,
Wrote on March 31, 2010 @ 5:31 am
testing
Dinesh said,
Wrote on April 9, 2010 @ 2:48 am
after logging how to get logged in user information?
Dinesh said,
Wrote on April 9, 2010 @ 2:56 am
Can any one plz tell how to get user information after logging in through twitter?
Software Creations - Orn Kristjansson · #swBoulder 2010 said,
Wrote on April 25, 2010 @ 4:37 pm
[...] 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 [...]
Paul said,
Wrote on April 27, 2010 @ 11:50 am
Shannon, thank for this informative post. Exactly what I was looking for.
pdub said,
Wrote on April 29, 2010 @ 2:39 pm
Thanks duder, helps out.
Jack said,
Wrote on May 3, 2010 @ 5:03 pm
Hi, getting a “You are not authorized to view this page” when clicking the full code link.
Thanks
Shannon Whitley said,
Wrote on May 3, 2010 @ 8:41 pm
@Jack Sorry, about that. The code has been updated for 1.0a and you can download it now.
Lee said,
Wrote on May 7, 2010 @ 3:42 am
Hi Shannon, I have this working fine if i run your demo but i don’t want the user to have to login to twitter every time they wish to post an update. I tried the following:
oAuth.AccessTokenGet(Request.QueryString["oauth_token"], Request.QueryString["oauth_verifier"]);
Session["Token"] = oAuth.Token;
Session["TokenSecret"] = oAuth.TokenSecret;
Session["OAuthVerifier"] = oAuth.OAuthVerifier;
Now i have the appropriate information stored in a session i then tried to post an update by using the following:
var oAuth = new oAuthTwitter();
oAuth.Token = Session["Token"].ToString();
oAuth.TokenSecret = Session["TokenSecret"].ToString();
oAuth.OAuthVerifier = Session["OAuthVerifier"].ToString();
oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, “http://twitter.com/statuses/update.xml”, oAuth.UrlEncode(“Test update!”));
However this does not work and throws back a 403 forbidden exception.
Appreciate if you could help.
vijai said,
Wrote on June 10, 2010 @ 4:56 pm
The code needs to be corrected.
There is a small typo which needs to be corrected in oAuthTwitter.cs. Here is the corrected code for the ConsumerSecret property.
public string ConsumerSecret {
get {
if (_consumerSecret.Length == 0)
{
_consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
}
return _consumerSecret;
}
set { _consumerSecret = value; }
}
Shannon Whitley said,
Wrote on June 11, 2010 @ 7:27 am
@Lee – Try it without setting the oAuthVerifier. That’s only needed during the initial token exchange.
@vijai – Thanks for catching that. I’ve updated the code.
AO said,
Wrote on June 15, 2010 @ 5:08 pm
To get around the 401 error for initial testing I commented out the line following:
//oAuth.CallBackUrl = “http://localhost”;
or you could also set:
oAuth.CallBackUrl = “oob”; //out of band
This will launch a log-in page or deny/approve page. Once user accepts you get a PIN number.
MeteoDenhelder said,
Wrote on July 16, 2010 @ 12:21 pm
Can Somebody mail me the standard zip file without errors. i have tried to get the errors out but i cant fix it.
My mail tinusrammstein at gmail.com
Kind gregards
Jason Meckel said,
Wrote on July 21, 2010 @ 8:16 am
Thanks for sharing this,
Is it ok to put Consumer secret inside the application ? Isn’t it supposed to be something I should keep away from user ?
Shannon Whitley said,
Wrote on July 22, 2010 @ 7:38 am
@Jason Meckel This particular article is for a web application. The key & secret would not be visible to the user.
For desktop applications, yes, you can modify the code so that the secret is inside the application. Even this is not completely safe since code can be decompiled. I don’t have an answer to that one.