0

How do I test if user supplied correct username/password for basic authentication?

I have this code to retrieve a page. If authentication is valid, it works fine

public static bool can_login(string user_name, string password)
{
    WebResponse response = null;
    StreamReader reader = null;
    string result = null;
    string login_url = "https://httpbin.org/basic-auth/user/passwd";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(login_url);
    request.Method = "GET";

    // Set the basic auth 
    string authInfo = user_name + ":" + password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    request.Headers["Authorization"] = "Basic " + authInfo;

    response = request.GetResponse(); // Throws System.Net.WebException if login invalid
    reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
    result = reader.ReadToEnd();

    return false;
}

Is there a foolproof way to test for correctness or should I just catch exception and hope its about the credentials?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ruslan
  • 1,919
  • 21
  • 42
  • http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba – Rob Jun 07 '16 at 04:47
  • 1
    Once catching the exception, you can inspect the status code returned, which should be consistent (relying on the third party site, though) – Rob Jun 07 '16 at 04:49

0 Answers0