C# HttpWebRequests在授权标头中发送无参数URI

C# HttpWebRequests在授权标头中发送无参数URI,c#,asp.net,httpwebrequest,C#,Asp.net,Httpwebrequest,我正在从.NET连接到web服务,如: var request = (HttpWebRequest) WebRequest.Create(uri); request.Credentials = new NetworkCredential("usr", "pwd", "domain"); var response = (HttpWebResponse) request.GetResponse(); 授权标头如下所示: Authorization: Digest username="usr",re

我正在从.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...
    ^^^^^^^^^^
Authorization: Digest username="usr", realm="domain", nonce="...", 
    uri="/dir/query?id=1", algorithm=MD5, etc...
    ^^^^^^^^^^^^^^^^^^^^^
服务器返回(400)个错误请求。Chrome或IE发送的标题如下所示:

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

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

看起来您需要安装此修补程序,这可能会帮助您:

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

还要确保预验证设置为true。

事实证明,这非常容易实现。通过我们自己的实现,我们能够使用完整的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();
    }
}
公共静态类DigestAuthFixer
{
私有静态字符串_host=”http://localhost";
私有静态字符串_user=“Mufasa”;
私有静态字符串\u password=“生命周期”;
私有静态字符串_领域;
私有静态字符串_nonce;
私有静态字符串_qop;
私有静态字符串;
私有静态日期时间\u cnonceDate;
私有静态int_nc;
私有静态字符串CalculateMd5Hash(
字符串输入)
{
var inputBytes=Encoding.ASCII.GetBytes(输入);
var hash=MD5.Create().ComputeHash(inputBytes);
var sb=新的StringBuilder();
foreach(散列中的变量b)
某人附加(b.ToString(“x2”));
使某人返回字符串();
}
私有静态字符串抓取器(
字符串varName,
字符串标题)
{
var regHeader=new Regex(string.Format(@“{0}=”“([^”“]*)”,varName));
var matchHeader=regHeader.Match(header);
if(matchHeader.Success)
返回matchHeader.Groups[1]。值;
抛出新的ApplicationException(string.Format(“未找到头{0}”,varName));
}
// http://en.wikipedia.org/wiki/Digest_access_authentication
私有静态字符串GetDigestHeader(
字符串目录)
{
_nc=_nc+1;
var ha1=CalculateMd5Hash(string.Format(“{0}:{1}:{2}”,_user,_realm,_password));
var ha2=CalculateMd5Hash(string.Format(“{0}:{1}”,“GET”,dir));
var消化反应=
CalculateMd5Hash(string.Format(“{0}:{1}:{2:00000000}:{3}:{4}:{5}”,ha1,_nonce,_nc,_cnon,_qop,ha2));
返回string.Format(“摘要用户名=\”{0}\”,领域=\“{1}\”,nonce=\“{2}\”,uri=\“{3}\”,”+
“algorithm=MD5,response=\“{4}\”,qop={5},nc={6:00000000},cnonce=\“{7}\”,
_用户、\u领域、\u当前、目录、摘要响应、\u qop、\u nc、\u cnonce);
}
公共静态字符串抓取响应(
字符串目录)
{
var url=_host+dir;
var uri=新的uri(url);
var request=(HttpWebRequest)WebRequest.Create(uri);
//如果我们有一个最近的Auth头,请重新使用它!
如果(!string.IsNullOrEmpty(\u cnence)&&
DateTime.Now.Subtract(\u cnonedate).TotalHours<1.0)
{
添加(“授权”,GetDigestHeader(dir));
}
HttpWebResponse;
尝试
{
response=(HttpWebResponse)request.GetResponse();
}
捕获(WebException ex)
{
//尝试通过添加授权标头来修复401异常
if(ex.Response==null | |((HttpWebResponse)ex.Response).StatusCode!=HttpStatusCode.Unauthorized)
投掷;
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(123400999999).ToString();
_cnonceDate=DateTime.Now;
var request2=(HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add(“授权”,GetDigestHeader(dir));
response=(HttpWebResponse)request2.GetResponse();
}
var reader=newstreamreader(response.GetResponseStream());
返回reader.ReadToEnd();
}
}

我最近遇到了这个问题。如果没有一些小的调整,我也无法从安多马尔那里找到解决办法。我把这些改变作为对安多马尔回答的一个建议,但是他们被泰曼和路西法毫不客气地拒绝了。因为我和一些同事花了好几个小时才弄明白这些,而且我相信其他人也会需要这些,所以我将代码作为答案发布出来

这是调整后的代码。基本上需要一个“不透明”的头变量,一些引号需要在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();
    }
}
公共静态类DigestAuthFixer
{
私有静态字符串_host=”http://localhost";
私有静态字符串_user=“Mufasa”;
私有静态字符串\u password=“生命周期”;
私有静态字符串_领域;
私有静态字符串_nonce;
私有静态字符串_qop;
私有静态字符串;
私有静态字符串_不透明;
私有静态日期时间\u cnonceDate;
私有静态int _nc=0;
私有静态字符串CalculateMd5Hash(
字符串输入)
{
var inputBytes=Encoding.ASCII.GetBytes(输入);
var hash=MD5.Create().ComputeHash(inputBytes);
var sb=新的StringBuilder();
foreach(散列中的变量b)
某人附加(b.ToString(“x2”));
使某人返回字符串();
}
私有静态字符串抓取器(
字符串varName,
字符串标题)
{
var regHeader=new Regex(string.Format(