Twitter oAuth with .NET for the Desktop
I 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 Tweetdeck. I don’t mind – it’s nice to know that the code is useful.
The original code that I provided was aimed at web applications. I haven’t had the need to develop any desktop apps lately and so I didn’t create any code for that style of oAuth. Quite frankly, I still find the desktop oAuth (using the PIN) to be a little awkward and I look forward to the promotion of xAuth by the Twitter team. However, someone asked me to create a sample desktop app using oAuth. I saw it as a challenge and decided to give it a try.
My first pass at the app popped up a web browser using ProcessInfo(). It worked, but I decided to go with the webcontrol to keep the user focused on the application. This form represents a one-time login page. After the login and PIN process, you can store the token and secret so that the user won’t need to login again (unless he or she revokes access for your application).
Once the user allows access to your application (screen shots above), a PIN will be displayed. The user must then enter that PIN in the textbox near the bottom of the screen. When the user clicks on the Update button, the PIN is used to retrieve the final credentials from Twitter.
When you add this to your project, you’ll need to include references to System.Web and System.Configuration. Other than that, it’s a pretty standard desktop application.
As I mentioned, I’m looking forward to Twitter’s general release of xAuth. That’s the type of authentication used by Seesmic Look. It’s a much smoother process for the user. Until then, I hope this code will help with your Twitter desktop applications.
p.s. – Of course I saw this post after I created my app (why does it always happen that way?). – GameTree – http://gametree.org/?p=245
data-text=”Twitter oAuth with .NET for the Desktop (Shannon Whitley)”
data-count=”vertical”
>Tweet
70 Responses to “Twitter oAuth with .NET for the Desktop”
Leave a Reply
7 Trackbacks
- Twitter xAuth with .NET | Shannon Whitley
[...] modified the code from my previous PIN-based desktop application example. Make sure you keep track of the token and secret that Twitter returns and save that in a [...]
- Twitter oAuth with .NET | Shannon Whitley
[...] Twitter oAuth with .NET for the Desktop [...]
- jayapenTells (jayan k jose)
“Twitter oAuth with .NET for the Desktop” (Shannon Whitley) [link to post] - Twitter oAuth in .Net without Web Login | PlanetB
[...] came across this article about how to use Twitter oAuth with .Net (via Twitter API documentation) and used the extended [...]
- Twitter oAuth with .NET for the Desktop Shannon Whitley
[...] Twitter oAuth with .NET for the Desktop Shannon Whitley. // [...]
- Implementing oauth twitter search in C# and JSON « Coder buddy
[...] implementation, and a JSON parser for extracting results. For oauth implementation I’m using Twitter oAuth with .NET by Shannon whitley and for parsing the results JSON parser by Procurious and i have to say that this post is just a [...]
- __sander (Sander Gerz)
Aanmeldingen voor dotNed meeting worden weer getweet. Even overstappen naar OAuth doe je zo [link to post]

I gave this some more thought and it occurred to me that I’m not doing enough to prove to the user that the login is going through Twitter. When I popped up a browser window, that was more evident. The webbrowser control is a better experience, but it does hide the fact that we really are going out to Twitter. I guess it still comes down to a matter of trust.
As usual, you did a good job. However, to make it easier for your readers, include a solution or project file, so that it is all included in one click.
Thanks @Mathias – I thought about doing that, but there are so many versions of Visual Studio that I try to keep it generic. Maybe I’ll change my mind now and include the project file.
Great work. Good Clean code without overcommenting. Oh and it works too
I am with @mathias you don’t hurt anything by including a project file. I like it when I can just click and hit run
If you have already stored the token and secret, then you can bypass all of the other code and just call the Twitter method from anywhere:
oAuthTwitter oAuth = new oAuthTwitter();
oAuth.Token = “{token}”;
oAuth.TokenSecret = “{secret}”;
url = “http://twitter.com/account/verify_credentials.xml”;
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
webBrowser1.DocumentText = HttpUtility.HtmlEncode(xml);
Added the project file to the zip file.
For some reason, that didn’t work for me Shannon. It gives me an “Unauthorized” message when I do so.
Maybe I am not storing the correct Token and Token Secret?
The Token I am storing for later use is the one I get from the AuthorizationLinkGet function, by grabbing the “oauth_token” value from the query string.
The Token Secret is grabbed from the oAuthTwitter.TokenSecret property after calling AccessTokenGet on a valid pincode. All of this works, but those tokens won’t use afterwards when used later.
[...] modified the code from my previous PIN-based desktop application example. Make sure you keep track of the token and secret that Twitter returns and save that in a [...]
[...] Twitter oAuth with .NET for the Desktop [...]
hi… do I need to login again and again on Twitter ..
@sujit – Once you have the token and secret for the user, you just store them and reuse them. There’s no need to have the user login again unless they revoke the rights to your application.
I downloaded this code and opened it with Visual Studio 2008 press F5 . Its Giveing Error Error
1 Resource file “Properties\Resources.resx” cannot be found. oAuthDesktopPINSample
Please Guid me what should i do ???
Thanx in advance
I am about to begin a book review column for an online newsletter, which I believe they must use Word Press to publish. I am trying to log into Word Press by clicking the ‘sign in with Twitter’ button. I allow TwitConnect access and it gives me a PIN but nowhere to enter the PIN? Am I missing something? Is there some sort of download I need that I don’t have? All the info I was given was to click on the ‘log into word press’ button on the newsletter site…
@Katy – Check the blog setup on Twitter. Make sure the “Application Type” is set to “browser” (not “client”):
http://dev.twitter.com/apps/
Twitter Comment
“Twitter oAuth with .NET for the Desktop” (Shannon Whitley) [link to post]
– Posted using Chat Catcher
Nice post.
I need your help. I have successfully verified the authorization from twitter.
Now i want to post a status update to the user’s twitter account but i want to use the same oauth_token and secret that was passed back by twitter.
I dont want the user to provide username or password.
How can i do it?
thanks
If you store the token and secret, you can reuse them for each call. Just create an oAuth object and set the token and secret to the previously stored objects before making the method call.
Thanks for the sample code Shannon. It was a great help in helping me get started with OAuth.
Note to @Dheeraj. Just start a new project and copy the source files into the project and you should be able to get the project to compile. It seems there are some resource files missing from the original project.
Note to others. I adapted this sample to get an OAuth token from Google. The encoding for parameters such as ‘scope’ fails because Google is expecting a character to escape special characters such as ‘:’ and ‘/’.
Again, thanks Shannon. The code was easy to follow and helped a lot.
@Andre – Thanks for the comments and I appreciate the extra help for the other folks too.
Is there a way to authenticate my desktop client without using a web browser control? I am trying to build a simple windows form app that takes user name and password from the user to authenticate and then be able to access followers, tweets, and tweets posted by my followers.
Please advice.
Is there a way to authenticate my desktop client without using a web browser control? I am trying to build a simple windows form app that takes user name and password from the user to authenticate and then be able to access followers, tweets, and tweets posted by my followers.
I’m trying to use OAuthUtility class.
Please advice.
Is there a way to authenticate my desktop client without using a web browser control? I am trying to build a simple windows form app that takes user name and password from the user to authenticate and then be able to access followers, tweets, and tweets posted by my followers.
I’m trying to use OAuthUtility class.
Please advice.
[...] came across this article about how to use Twitter oAuth with .Net (via Twitter API documentation) and used the extended [...]
Nice post…. I have found it after wasting a lot of hours…
I have a query though… I am having this exception in OAuth Class in the
public string GenerateSignatureBase()
I am having this exception due to value of ConsumerKey is Null…. Need help ASAP!
@Farrukh, I think there’s a bug in Shannon’s code. In the oAuthTwitter class, I think I had to change the ConsumerKey Get property to return the _consumerKey variable. Something like that. I kinda forget, but yes, I was getting the same error.
@Farrukh – Thank you. Please enter the consumer key and secret in the app.config file. It sounds like you haven’t updated app.config.
Thanks for the help @Jamie. There was a bug where you couldn’t set the consumer secret through code. I fixed that.
I am still getting the hang of oauth but I was reading your posts and it sounds like in order to access a specific users profile; I need to send an authorization request to the twitter site get an authorized key which i need to use to then access a users profile or does the authorization request go to the user and if so how does the user receive this request and authorize it and how long does this take. It seems as if the authorization screen will pop up on my machine. Am I understanding this correctly?
Hi @Jack,
The entire process is normally initiated and completed on the user’s desktop. Your application requests the keys from Twitter based on user interaction. Authorization requests aren’t “sent” anywhere. The authorization request is presented to the user as part of a single process.
If you want to access a user’s profile, the user will need to be directed to a web page with the authorization process or the desktop app will need to include the authorization process.
It helps to know what type of application you’re building to point you in the right direction.
Hi Shannon, very nice code and good understandable.
But I was very hopeless yesterday.
I tried to post a tweed. Found your sample code and it work well the first time. Further calls ever returned ’403 forbidden’. Hours later the same. It works once and than I got ‘forbidden’ from Http-Request.
I was nearly to rotate amok.
Today I had the enligthment.
Twitter blocked the post because my sample programm ever posted the same content. Adding GetDate and it worked well
Perhaps anybody has the same problem.
Thnaks to you Shannon
Hello,
I’m developing a Desktop App for twitter. I want a feature to login multiple users at once and too without showing the login screen everytime (keep the session details). Can’t find a solution for this. Can anybody help me out for this. A working code would be really appreciated.
Thanks and Regards,
Varun Jain
[...] Twitter oAuth with .NET for the Desktop Shannon Whitley. // [...]
[...] implementation, and a JSON parser for extracting results. For oauth implementation I’m using Twitter oAuth with .NET by Shannon whitley and for parsing the results JSON parser by Procurious and i have to say that this post is just a [...]
I getting Exception for Consumer Key. what value should Consumer Key have in app.config file
@Sachin Bhalerao – This is the API Key for your application fro http://dev.twitter.com/apps.
Shannon,
Thanks for all you hard work on this desktop app! This code looks like just the help I need to tackle oAuth in my own app.
I’m using Visual Studio 2010; I opened your project, went through the upgrade wizard, set my consumer key and secret in app.config and attempted to run.
I got a popup from Windows saying that it had detected that the app did not run correctly. I tried running again and got a form with nothing in the window.
Any suggestions?
Nevermind! I went up to my Twitter app settings page and reset my consumer/key secret, then copy/pasted it into my app.config.
Bingo! The desktop app came up.
Thanks again!
Is there a way to authenticate my desktop client without using a web browser control?
Twitter Comment
Aanmeldingen voor dotNed meeting worden weer getweet. Even overstappen naar OAuth doe je zo [link to post]
– Posted using Chat Catcher
Thank you for this excellent example and the oAUTH code. And those who encounter the same errors as I have here are some tips.
For this to work for me, I had to host the app on an actual web server that’s open to the public and had to modify http://localhost call back to the URL of where I was testing from, again, the same server on my case. I have subsequently stumbled with 401 then 403 errors.
The (401) Unauthorized error for me was I was not doing it from a public web server. As soon as the URL matched with the server where the initial request was sent from, that went away.
The (403) Forbidden error was definitely due to my posting the same test messages over and over again, and the example will work. If your first message has worked but not afterwards, try sending different messages, such as appending DateTime.Now.ToLongTimeString()
Now I need to figure out how to modify this code so that I can Tweet machine generated messages from a service program (wave status etc.) I am hoping that if I preserve all of the authentication parameters, I can reuse them to post, and hoping that I do not need to get a new token for each post…
Hi Shannon,
I’m now trying to tweet using your example code, but it’s failing:
string xml = “”;
string url = “”;
oAuthTwitter oAuth = new oAuthTwitter();
oAuth.ConsumerKey = “myConsumerKey”;
oAuth.ConsumerSecret = “myConsumerSecret”;
oAuth.Token = “myToken”;
oAuth.TokenSecret = “myTokenSecret”;
//POST Test
url = “http://twitter.com/statuses/update.xml”;
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, “status=” + oAuth.UrlEncode(“Hello, Twitter! From the twittibot”));
Any suggestions?
Thanks in advance!
@Manabu – Great tips. Yes, I’ve hit the 403 duplicate post error (no help from the error message).
@Twitti – Make sure you have the latest code. There was a version that only pulled the ConsumerSecret from the config file. And make sure it isn’t a duplicate post, as noted by @Manabu.
Looking for a more simple command line programme for dos to post a tweet.
Like: c:\twitter_programme -p “my twitter text” -t “tokens” … etc….
You see anything like this? My coding ability is limited.
@Bl – Yes, I have seen something like that. Search for “Twitter Command Line” and you’ll see several options. I haven’t tried any of them.
Thanks for your information.
I implemented all the functions without any errors.
I stored the consumer key and the consumer secret from the registered application in Twitter.
I got the access token and access token verifier from the query string received after clicking on “Allow” button giving my valid twitter account details and it returned back to my call back URL with a query consists oauth_token as well oauth_token_verifier and stored these values for later purpose.
If I use the oauth_token and oauth_token_verifier for later for sending the tweets or after the first time verification. Get the exception as “401 unauthorized”. I know I did a small mistake but do not know where.
Will you just explain me the basic details should be collected and stored for later purpose to avoid the authorization process again and again else avoiding the error “401 unauthorize”.
Hi @Andrew – Do NOT use the oauth_verifier in any calls except the very first one. Drop that variable for all subsequent calls. Only include the oauth token and secret.
Just added to the above details posted by me. I am just creating a web application and I tried the followings also to diagnose the error and rectify it.
1. Initially, I set http://localhose:xxxx/thepagename.aspx through code. It just over writes the call back URL set at the app setting in the twitter. I just removed this and executed also with the registered application in the www but exception arises.
2. I just stored the nonce also since it is generated randomly and referred at the future access, but the exception arises even.
So, I would like to know what details can be stored exactly for future references to avoid the authentication repeatedly unless the user revokes me from his twitter.
I am again back with some challenges in oAuth implementation.
I deployed in the www host and tried the oAuth functionality. The unexpected error is; When I execute with the localhost for testing purpose, it returns two query strings oauth_token as well oauth_verifier but it returns only one query string named oauth_token. The other one is missing.
NOTE: I am implementing the oAuthTwitter and oAuthBase classes available in the googledocs in my web application.
Let me know your suggestions also to avoid the 401 unauthorized error.
after downloading the code what is the process for running the app.i have stored all the keys.but where should i enter those keys.iam getting consumer key error..
As mentioned elsewhere. 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();
}
Thanks for this code! I found lots of OAuth info on the web but no one was able to put it all together in a “This is what you do” format.
Thanks for saving me days of work.
@srikanth – The keys go in the {app name}.config file.
@John – I’m happy to help. Thanks for letting me know. I appreciate it.