【问题标题】:HttpWebRequests sends parameterless URI in Authorization headerHttpWebRequest 在授权标头中发送无参数 URI
【发布时间】:2010-06-24 11:31:40
【问题描述】:

我正在从 .NET 连接到 Web 服务,例如:

var request = (HttpWebRequest) WebRequest.Create(uri);
request.Credentials = new NetworkCredential("usr", "pwd", "domain");
var response = (HttpWebResponse) request.GetResponse();

授权标头如下:

Authorization: Digest username="usr",realm="domain",nonce="...",
    uri="/dir",algorithm="MD5",etc...
    ^^^^^^^^^^

服务器返回 (400) 错误请求。 Chrome 或 IE 发送的标头如下所示:

Authorization: Digest username="usr", realm="domain", nonce="...", 
    uri="/dir/query?id=1", algorithm=MD5, etc...
    ^^^^^^^^^^^^^^^^^^^^^

我们怀疑 URI 的差异导致 Web 服务以 400 错误拒绝请求。是否可以让 HttpRequest 发出包含完整 URI 的 Authorization 标头?

【问题讨论】:

  • 您使用什么 URI 创建 Web 请求?它是否包含“query?id=1”部分?
  • 另外,你能从浏览器获得成功请求的wireshark跟踪吗?然后比较两者。我怀疑它可能与 auth 标头没有任何关系。如果 auth 标头不正确,您将收到 401 响应(不是 400)
  • @feroze:问题中的两个标题都来自 Wireshark。如果此特定服务器认为授权标头中的 URI 不正确,则返回 400 而不是 401
  • 查看参考源,似乎查询部分已被故意删除,因为“它破坏了 IIS6”:referencesource.microsoft.com/#System/net/System/Net/…

标签: c# asp.net httpwebrequest


【解决方案1】:

事实证明Digest authentication 相当容易实现。通过我们自己的实现,我们能够使用完整的 URI(包括参数)来生成 MD5 哈希。这解决了问题。

如果将来有人遇到此问题,您可以调用以下解决方法:

var resultText = DigestAuthFixer.GrabResponse("/dir/index.html");

DigestAuthFixer 类的代码:

public static class DigestAuthFixer
{
    private static string _host = "http://localhost";
    private static string _user = "Mufasa";
    private static string _password = "Circle Of Life";
    private static string _realm;
    private static string _nonce;
    private static string _qop;
    private static string _cnonce;
    private static DateTime _cnonceDate;
    private static int _nc;

    private static string CalculateMd5Hash(
        string input)
    {
        var inputBytes = Encoding.ASCII.GetBytes(input);
        var hash = MD5.Create().ComputeHash(inputBytes);
        var sb = new StringBuilder();
        foreach (var b in hash)
            sb.Append(b.ToString("x2"));
        return sb.ToString();
    }

    private static string GrabHeaderVar(
        string varName,
        string header)
    {
        var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
        var matchHeader = regHeader.Match(header);
        if (matchHeader.Success)
            return matchHeader.Groups[1].Value;
        throw new ApplicationException(string.Format("Header {0} not found", varName));
    }

    // http://en.wikipedia.org/wiki/Digest_access_authentication
    private static string GetDigestHeader(
        string dir)
    {
        _nc = _nc + 1;

        var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
        var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
        var digestResponse =
            CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));

        return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
            "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
            _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
    }

    public static string GrabResponse(
        string dir)
    {
        var url = _host + dir;
        var uri = new Uri(url);

        var request = (HttpWebRequest)WebRequest.Create(uri);

        // If we've got a recent Auth header, re-use it!
        if (!string.IsNullOrEmpty(_cnonce) &&
            DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
        {
            request.Headers.Add("Authorization", GetDigestHeader(dir));
        }

        HttpWebResponse response;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException ex)
        {
            // Try to fix a 401 exception by adding a Authorization header
            if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
                throw;

            var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
            _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
            _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
            _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);

            _nc = 0;
            _cnonce = new Random().Next(123400, 9999999).ToString();
            _cnonceDate = DateTime.Now;

            var request2 = (HttpWebRequest)WebRequest.Create(uri);
            request2.Headers.Add("Authorization", GetDigestHeader(dir));
            response = (HttpWebResponse)request2.GetResponse();
        }
        var reader = new StreamReader(response.GetResponseStream());
        return reader.ReadToEnd();
    }
}

【讨论】:

  • 嗯 - 这听起来像一个错误。我在 Microsoft Connect 网站上打开了一个问题。随意登录并添加有关 Uri 和操作系统、.net 框架版本等的更多详细信息。这里是连接问题 Uri:connect.microsoft.com/VisualStudio/feedback/details/571052/…
  • 这个答案可以通过使其线程安全(而不是使用共享 static 状态)、正确处理 IDisposable 对象以及其他 FxCop 合规修复来改进。
【解决方案2】:

我最近遇到了这个问题。如果没有一些小的调整,我也无法从 Andomar 获得解决方法。我将更改作为对 Andomar 答案的建议提交,但被 TheTinMan 和 Lucifer 毫不客气地拒绝了。由于我和一些同事花了几个小时才弄清楚这些,而且我相信其他人会需要这个,所以我发布了代码作为答案以使其可用。

这是调整后的代码。基本上需要一个“不透明”的标头变量,并且需要在 GetDigestHeader 中修复一些引号。

public static class DigestAuthFixer
{
    private static string _host = "http://localhost";
    private static string _user = "Mufasa";
    private static string _password = "Circle Of Life";
    private static string _realm;
    private static string _nonce;
    private static string _qop;
    private static string _cnonce;
    private static string _opaque;
    private static DateTime _cnonceDate;
    private static int _nc = 0;

    private static string CalculateMd5Hash(
        string input)
    {
        var inputBytes = Encoding.ASCII.GetBytes(input);
        var hash = MD5.Create().ComputeHash(inputBytes);
        var sb = new StringBuilder();
        foreach (var b in hash)
            sb.Append(b.ToString("x2"));
        return sb.ToString();
    }

    private static string GrabHeaderVar(
        string varName,
        string header)
    {
        var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
        var matchHeader = regHeader.Match(header);
        if (matchHeader.Success)
            return matchHeader.Groups[1].Value;
        throw new ApplicationException(string.Format("Header {0} not found", varName));
    }

    // http://en.wikipedia.org/wiki/Digest_access_authentication
    private static string GetDigestHeader(
        string dir)
    {
        _nc = _nc + 1;

        var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
        var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
        var digestResponse =
            CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));

        return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
        "algorithm=MD5, response=\"{4}\", qop=\"{5}\", nc=\"{6:00000000}\", cnonce=\"{7}\", opaque=\"{8}\"",
        _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce, _opaque);
    }

    public static string GrabResponse(
        string dir)
    {
        var url = _host + dir;
        var uri = new Uri(url);

        var request = (HttpWebRequest)WebRequest.Create(uri);

        // If we've got a recent Auth header, re-use it!
        if (!string.IsNullOrEmpty(_cnonce) &&
            DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
        {
            request.Headers.Add("Authorization", GetDigestHeader(dir));
        }

        HttpWebResponse response;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException ex)
        {
            // Try to fix a 401 exception by adding a Authorization header
            if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
                throw;

            var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
            _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
            _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
            _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
            _opaque = GrabHeaderVar("opaque", wwwAuthenticateHeader);
            _nc = 0;
            _cnonce = new Random().Next(123400, 9999999).ToString();
            _cnonceDate = DateTime.Now;

            var request2 = (HttpWebRequest)WebRequest.Create(uri);
            request2.Headers.Add("Authorization", GetDigestHeader(dir));
            response = (HttpWebResponse)request2.GetResponse();
        }
        var reader = new StreamReader(response.GetResponseStream());
        return reader.ReadToEnd();
    }
}

【讨论】:

  • 我同意。您的修复是绝对必要的。
  • 你知道为什么我将 WWW-Authenticate" 设为 null 吗?
【解决方案3】:

看来您需要安装此修补程序可能会对您有所帮助:

http://support.microsoft.com/?kbid=924638

您的问题可能是因为您在使用 HTTP 适配器发布消息时无法将 KeepAlive 属性设置为 false

还要确保 PreAuthenticate 设置为 true。

【讨论】:

  • 这看起来像是 BizTalk 的修复程序。我们没有使用 BizTalk,我可以将 KeepAlive 和 PreAuthenticate 设置为 true:结果相同
猜你喜欢
  • 2020-05-22
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 2020-03-28
  • 2017-12-04
  • 1970-01-01
相关资源
最近更新 更多