Question

How can I read the Realm property sent in the WWW-Authenticate header by a server requesting HTTP Basic authentication?

Was it helpful?

Solution

Not really sure what the issue the down-voters have with this question really is.

Here's the rough code to get the WWW-Authenticate header that contains the Basic authentication realm. Extracting the actual realm value from the header is left as an exercise, but should be quite straightforward (e.g. using regular expression).

public static string GetRealm(string url)
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    try
    {
        using (request.GetResponse())
        {
            return null;
        }
    }
    catch (WebException e)
    {
        if (e.Response == null) return null;
        var auth = e.Response.Headers[HttpResponseHeader.WwwAuthenticate];
        if (auth == null) return null;
        // Example auth value:
        // Basic realm="Some realm"
        return ...Extract the value of "realm" here (with a regex perhaps)...
    }
}

OTHER TIPS

I'm assuming you want to create a Web Request with Basic Authentication.

If that's the correct assumption, the following code is what you need:

// Create a request to a URL
WebRequest myReq = WebRequest.Create(url);
string usernamePassword = "username:password";
//Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top