Question

Bounty Question

I am using c# 3.5 Window Forms Application. I am using the code mentioned in the accepted answer. and I am getting below error

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

Sample code to verify the UserName and Password will be really appreciated

Bounty Question Ends


I have an application with the following use-case: when the user first starts using the application, he inputs his username and password. Then, at a much later stage, the application may update his status.

Currently I'm using Twitterizer, but I believe the question is beyond the scope of the specific library I'm using. Following are the two relevant lines of code:

Twitter twitter = new Twitter("username", "password", "source"); 
twitter.Status.Update("update");

The construction of the Twitter object does not throw an exception if the username/password are incorrect. This is probably because nothing is sent at this point. On the other hand, the status update does throw an exception if the username/password are invalid.

My problem is that I want to validate the username/password at the point of user input, not when trying to post the update.

How can I validate the username/password without posting anything (in Twitterizer or otherwise)?

Was it helpful?

Solution

Taking a quick look at the verify_credentials API as mentioned by peSHIr, I wrote a little routine which seems to do the trick. It's late, but I was able to test it a couple of times and seems to work.

In my function, I am just returning true if I I get an HttpResponseCode.OK, and false if I get anything else or an exception is thrown. If twitter does not like the uid/password an exception will be thrown with a 401 error (not authorized.)

public bool CheckTwitterCredentials(string UserName, string Password)
{
    // Assume failure
    bool Result = false;

    // A try except block to handle any exceptions
    try {
        // Encode the user name with password
        string UserPass = Convert.ToBase64String(
            System.Text.Encoding.UTF8.GetBytes(UserName + ":" + Password));

        // Create our HTTP web request object
        HttpWebRequest Request = 
            (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml");

        // Set up our request flags and submit type
        Request.Method = "GET";
        Request.ContentType = "application/x-www-form-urlencoded";

        // Add the authorization header with the encoded user name and password
        Request.Headers.Add("Authorization", "Basic " + UserPass);

        // Use an HttpWebResponse object to handle the response from Twitter
        HttpWebResponse WebResponse = (HttpWebResponse)Request.GetResponse();

        // Success if we get an OK response
        Result = WebResponse.StatusCode == HttpStatusCode.OK;
    } catch (Exception Ex) {
        System.Diagnostics.Debug.WriteLine("Error: " + Ex.Message);
    }

    // Return success/failure
    return Result;
}

OTHER TIPS

You could try to use the API call account/verify_credentials. Hopefully the API library you use already supports this.. Twitter is notorious now for really hating third party programmers, so unless you have good reason to do something with Twitter, just stay away...

I have used other Twitter Libraries but none of them support checking the username and password for validitity. This might be because Twitter API does not have the facility to validate the username and password unless we try to do something which requires authentication.

One thing you can do is try to get friend list or any other methods that requires authentication.

Twitter API hasn't supported username/password in years. Instead, you have OAuth, which lets the user authorize your application to act on their behalf. Twitter has an account/verify_credentials endpoint you can use to verify whether the user who's tokens you have still authorizes your app. Here's an example of how you could call this endpoint with LINQ to Twitter:

        var accounts =
            from acct in twitterCtx.Account
            where acct.Type == AccountType.VerifyCredentials
            select acct;

You can visit Account/VerifyCredentials documentation for more details:

as @joe-mayo informed, you have to switch to OAuth. twitter expired v1 of their API and they documented that in following url https://dev.twitter.com/docs/faq#17750.

Here's a function i wrote that will verify twitter username and password in C# :

public bool isTwitterValid(string username, string password)
{
    try
    {
        string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://twitter.com/statuses/verify.xml");

        request.Method = "POST";
        request.ServicePoint.Expect100Continue = false;
        request.Headers.Add("Authorization", "Basic " + user);
        request.ContentType = "application/x-www-form-urlencoded";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseString = reader.ReadToEnd();
        reader.Close();
    }
    catch (Exception ex)
    {
        if (ex.Message.Contains("404")) { return true; }
    }
    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top