Search code examples
c#httpwebrequestbasic-authenticationwebresponse

Read the Realm property in HTTP authentication


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


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)...
        }
    }