读取HTTP身份验证中的Realm属性



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

我不太确定选民对这个问题到底有什么看法。

下面是获取包含基本身份验证领域的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)...
    }
}

我假设你想创建一个带有基本身份验证的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();

相关内容

  • 没有找到相关文章

最新更新