Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot authenticate with twitter using dotnetopenauth

Hi I am trying to give users of my site the ability to login with twitter. I would like to register my app with localhost so that I can test. Due to twitter not accepting this I changed the url to 127.0.0.1 I also tried adding the portnumber. I entered my secrets in the AuthConfig File. When I click on the twitter button I get the error

The remote server returned an error: (401) Unauthorized.

I then began to run my app on iis to fix a problem that my site couldn't login with my windows live account (that sorted that problem) but I still get this Unauthorized error. Someone please help.

Thank you

like image 734
David Avatar asked Feb 18 '23 18:02

David


1 Answers

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);
}
like image 184
levelnis Avatar answered Feb 20 '23 06:02

levelnis