Reputation: 3175
I'm using the C# Twitterizer in a WPF application to authenticate users to Twitter so I can publish tweets to their stream. (But that's irrelevant because the question is about the API itself).
I do not wish to create a new login interface, I want to use Twitter's Login page embedded in a WebBrowser control. Does Twitter support the same authentication style as Facebook where the user logs in to the regular FB login page and the access token is sent back in the callback URL? Or sending the username and password is the only way to get an access token (in Twitter)?!
Upvotes: 0
Views: 1117
Reputation: 192467
Here's an Oauth 1.0a class that works with Twitter, and allows what you want.
There's also a simple example that shows how to use the class.
The code looks like this:
OAuth.Manager oauth;
AuthSettings settings;
public void Foo()
{
oauth = new OAuth.Manager();
oauth["consumer_key"] = TWITTER_CONSUMER_KEY;
oauth["consumer_secret"] = TWITTER_CONSUMER_SECRET;
settings = AuthSettings.ReadFromStorage();
if (VerifyAuthentication())
{
Tweet("Hello, World");
}
}
private void Tweet(string message)
{
var url = "http://api.twitter.com/1/statuses/update.xml?status=" + message;
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
...
}
}
}
private bool VerifyAuthentication()
{
if (!settings.Completed)
{
var dlg = new TwitterAppApprovalForm(); // your form with an embedded webbrowser
dlg.ShowDialog();
if (dlg.DialogResult == DialogResult.OK)
{
settings.access_token = dlg.AccessToken;
settings.token_secret = dlg.TokenSecret;
settings.Save();
}
if (!settings.Completed)
{
MessageBox.Show("You must approve this app for use with Twitter\n" +
"before updating your status with it.\n\n",
"No Authorizaiton for TweetIt",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return false;
}
}
// apply stored information into the oauth manager
oauth["token"] = settings.access_token;
oauth["token_secret"] = settings.token_secret;
return true;
}
The TwitterAppApprovalForm
is boilerplate, and is included in the example. When you have no cached access_token and token-secret, then that form pops open, hosting an embedded webbrowser that displays the Twitter authorization form. If you have the cached data, then you don't need to display that form.
Upvotes: 1
Reputation: 1183
Yes, Twitter seupports the same authentication style than Facebook called OAuth. Facebook uses OAuth 2 and Twitter uses OAuth 1.0a
Take a look to Spring.NET Social Twitter : http://springframework.net/social-twitter/ It provides samples for what you are trying to do.
Upvotes: 0