2

如何读取请求 HTTP Basic 身份验证的服务器在 WWW-Authenticate 标头中发送的 Realm 属性?

4

2 回答 2

8

不确定投票者对这个问题的真正问题是什么。

这是获取包含基本身份验证领域的 WWW-Authenticate 标头的粗略代码。从标题中提取实际的领域值作为练习,但应该非常简单(例如使用正则表达式)。

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)...
    }
}
于 2011-12-08T22:15:21.983 回答
2

我假设您想创建一个带有基本身份验证的 Web 请求。

如果这是正确的假设,那么您需要以下代码:

// 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();
于 2011-12-08T20:20:04.947 回答