1

In my program I am trying to access a website which is password protected (when opened in browser, a pop-up like this one on the picture shows up requiring the user to log in (note: this is just a picture found on google, not the actual site I am using)). The pop-up login prompt

Now, I don't need exactly to open this site (actually it's subdirectory) or download it or anything, I just want to verify the login info. Say there would be two textboxes in the application, similiar to those that would pop-up in the browser, and I want to verify if the entered username and password are correct. Any idea how? My idea would be trying to act like it would be an FTP file, since that's the only way I could figure out how to set the login name and password in the code, and I expected that if the credentials would be incorrect, the program would drop an exception or something, but it just goes through this code with no result.

Thanks for any help

Marek Buchtela
  • 973
  • 3
  • 19
  • 42

1 Answers1

4

You could try to do an http request to the url and give the credentials with the request. If the response is of status code 200 (OK) everything is ok. If response is of status code 401 (Unauthorized), then the credentials are not ok:

// create request
var request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.Credentials = new NetworkCredential("Username", "Password");

try
{
    // get response
    var response = (HttpWebResponse)request.GetResponse();
    var statusCode = response.StatusCode;

    // verify response
    if (statusCode == HttpStatusCode.OK)
    {
        // login was ok
    }
}
catch (WebException ex)
{
    if (((HttpWebResponse) ex.Response).StatusCode == HttpStatusCode.Unauthorized)
    {
        // unauthorized
    }
}
Kevin Brechbühl
  • 4,717
  • 3
  • 24
  • 47
  • Tried this, on line with request.GetResponse(); an exception is thrown - WebException was unhandled, The remote server returned an error: (401) Unauthorized. – Marek Buchtela Mar 17 '14 at 12:22
  • @MarekBuchtela This means that your login failed. I changed the code a little bit because it threw an exception. Please see my updated answer. – Kevin Brechbühl Mar 17 '14 at 14:41
  • No, I meant, the exception is thrown even if I enter a correct password – Marek Buchtela Mar 18 '14 at 21:31
  • @MarekBuchtela I've tested this code above and it worked fine for me. If you browse the website with a browser and enter the correct credentials, which status code do you receive? – Kevin Brechbühl Mar 19 '14 at 06:10