CoderWalker
CoderWalker

Reputation: 299

C# WebRequest Check if page requires HTTP Authentication

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>";
}
?>

Upvotes: 2

Views: 1499

Answers (2)

Andre Calil
Andre Calil

Reputation: 7692

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

Upvotes: 4

David
David

Reputation: 2920

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

Upvotes: 1

Related Questions