I had exactly the same problem and couldn't solve it with DotNetOpenAuth
no matter what I tried. The authentication process for Twitter is far more difficult to get right than either Facebook or Google+ when using DotNetOpenAuth
as it comes. After many frustrating hours, encrypting and encoding various parts of the data varying numbers of times and always getting the unhelpful 401 unauthorised, I added Tweetsharp into the mix and created my own IAuthenticationClient
for Twitter authentication. It's fairly simple to perform the authentication with Tweetsharp
. It becomes a relatively trivial matter of this:
In your TwitterClient
constructor:
var twitterService = new TwitterService(consumerKey, consumerSecret);
In your implementation of IAuthenticationClient
:
public void RequestAuthentication(HttpContextBase context, Uri returnUrl)
{
var requestToken = twitterService.GetRequestToken(returnUrl.AbsoluteUri);
var redirectUrl = twitterService.GetAuthorizationUri(requestToken).AbsoluteUri;
context.Response.Redirect(redirectUrl, true);
}
public AuthenticationResult VerifyAuthentication(HttpContextBase context)
{
var oAuthToken = context.Request.QueryString["oauth_token"];
var oAuthVerifier = context.Request.QueryString["oauth_verifier"];
var requestToken = new OAuthRequestToken { Token = oAuthToken };
var accessToken = twitterService.GetAccessToken(requestToken, oAuthVerifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
var user = twitterService.VerifyCredentials();
var userId = user.Id.ToString();
var extraData = new Dictionary<string, string>
{
{"accesstoken", accessToken.Token},
{"accesstokensecret", accessToken.TokenSecret},
{"id", userId},
{"name", user.Name},
{"username", user.ScreenName},
{"link", user.Url},
};
return new AuthenticationResult(true, ProviderName, userId, user.ScreenName, extraData);
}