2

Does anyone know how to check if a webpage is asking for HTTP Authentication via C# using the WebRequest class? I'm not asking how to post Credentials to the page, just how to check if the page is asking for Authentication.

Current Snippet to get HTML:

WebRequest wrq = WebRequest.Create(address);
wrs = wrq.GetResponse();
Uri uri = wrs.ResponseUri;
StreamReader strdr = new StreamReader(wrs.GetResponseStream());
string html = strdr.ReadToEnd();
wrs.Close();
strdr.Close();
return html;

PHP Server side source:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Secure Sign-in"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
user229044
  • 232,980
  • 40
  • 330
  • 338
CoderWalker
  • 299
  • 4
  • 14

2 Answers2

4

WebRequest.GetResponse returns an object of type HttpWebResponse. Just cast it and you can retrieve StatusCode.

However, .Net will give you an exception if it receives a response of status 4xx or 5xx (thanks for your feedback). There is a little workaround, check it out:

    HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(@"http://webstrand.comoj.com/locked/safe.php");
    HttpWebResponse wrs = null;

    try
    {
        wrs = (HttpWebResponse)wrq.GetResponse();
    }
    catch (System.Net.WebException protocolError)
    {
        if (((HttpWebResponse)protocolError.Response).StatusCode == HttpStatusCode.Unauthorized)
        {
            //do something
        }
    }
    catch (System.Exception generalError)
    {
        //run to the hills
    }

    if (wrs.StatusCode == HttpStatusCode.OK)
    {
        Uri uri = wrs.ResponseUri;
        StreamReader strdr = new StreamReader(wrs.GetResponseStream());

        string html = strdr.ReadToEnd();
        wrs.Close();
        strdr.Close();
    }

Hope this helps.

Regards

Andre Calil
  • 7,652
  • 34
  • 41
1

Might want to try

WebClient wc = new WebClient();
CredentialCache credCache = new CredentialCache();

If you can work with WebClient instead of WebRequest, you should it's a bit higher level, easier to handle headers etc.

Also, might want to check this thread: System.Net.WebClient fails weirdly

Community
  • 1
  • 1
David
  • 2,715
  • 2
  • 22
  • 31