如何使用HttpWebRequest进行摘要认证?

22

我发现的多篇文章(12)都让这个看起来很容易:

WebRequest request = HttpWebRequest.Create(url);

var credentialCache = new CredentialCache();
credentialCache.Add(
  new Uri(url), // request url
  "Digest", // authentication type
  new NetworkCredential("user", "password") // credentials
);

request.Credentials = credentialCache;

但是,这仅适用于没有URL参数的URL。例如,我可以成功下载http://example.com/test/xyz.html,但当我尝试下载http://example.com/test?page=xyz时,结果是一个带有以下内容的400 Bad Request消息在服务器记录中(运行Apache 2.2):

Digest: uri mismatch - </test> does not match request-uri </test?page=xyz>

我的第一个想法是摘要规范要求从摘要哈希中删除URL参数,但是从传递给credentialCache.Add()的URL中删除参数并没有改变任何内容。因此,它一定是相反的方式,在.NET框架中错误地删除了URL的参数。


这里有一个类似的问题在SO上,我的初始搜索没有得到结果: https://dev59.com/-U7Sa4cB1Zd3GeqP5KSk - Cygon
还有一个微软连接错误报告:https://connect.microsoft.com/VisualStudio/feedback/details/571052/digest-authentication-does-not-send-the-full-uri-path-in-the-uri-parameter - Cygon
上面链接的 Microsoft Connect 缺陷报告似乎有一个解决方法,发布于6/26。你试过了吗? - Samuel Meacham
是的,那样做可以解决它。但是从.NET Framework的角度来看,这实际上是一种变通方法,因为它重新实现了功能。我希望这只是我在使用HttpWebRequest类时犯了一个错误。 - Cygon
1
甚至在Apache的mod_auth_digest(执行摘要身份验证的模块)中,还有一个hack来解决Internet Explorer发生的同样问题:http://httpd.apache.org/docs/2.0/mod/mod_auth_digest.html#msie - Cygon
5个回答

11

这篇文章中的代码对我非常有效。 在C#中通过HttpWebRequest实现摘要认证

我遇到了以下问题,每当我在浏览器中浏览Feed URL时,它都会要求输入用户名和密码,并且能够正常工作,但是上述任何一种代码示例都无法正常工作。在检查请求/响应标头(在Firefox的Web开发人员工具中)时,我可以看到标头具有摘要类型的授权。

步骤1添加:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace NUI
{
    public class DigestAuthFixer
    {
        private static string _host;
        private static string _user;
        private static string _password;
        private static string _realm;
        private static string _nonce;
        private static string _qop;
        private static string _cnonce;
        private static DateTime _cnonceDate;
        private static int _nc;

    public DigestAuthFixer(string host, string user, string password)
    {
        // TODO: Complete member initialization
        _host = host;
        _user = user;
        _password = password;
    }

    private 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 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));
    }

    private 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 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 digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);

如果Url是:http://xyz.rss.com/folder/rss 那么 域名: http://xyz.rss.com (域名部分) 目录:/folder/rss (url的其余部分)

你也可以将其作为流返回并使用XmlDocument Load()方法。


很棒的文章。我有一个问题,当我获取 var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"]; 时,它为 null,可能的原因是什么? - Alexander Gorelik
非常感谢你,兄弟。我已经在这里奋斗了两天。这对我很有效。 - Andrés Mauricio Gómez

9
您说您已经删除了查询字符串参数,但是您是否尝试过只使用主机名?我看到的每个CredentialsCache.Add()的例子都似乎只使用了主机名,而CredentialsCache.Add()的文档中将Uri参数列为“uriPrefix”,这似乎很有意思。
换句话说,请尝试以下方法:
Uri uri = new Uri(url);
WebRequest request = WebRequest.Create(uri);

var credentialCache = new CredentialCache(); 
credentialCache.Add( 
  new Uri(uri.GetLeftPart(UriPartial.Authority)), // request url's host
  "Digest",  // authentication type 
  new NetworkCredential("user", "password") // credentials 
); 

request.Credentials = credentialCache;

如果这样做成功了,你还需要确保不要将相同的“权限”添加到缓存中超过一次... 所有对同一主机的请求都应该能够利用相同的凭证缓存条目。

奇怪,我没有遇到过只使用根URI进行身份验证的示例。无论如何,它都不起作用,抱歉。根据RFC 2617第3.2.2节(http://rfc.askapache.com/rfc2617/rfc2617.html#section-3.2.2),摘要URI应与HTTP请求中的'request-uri'相同。 - Cygon
以下是一些示例:http://msdn.microsoft.com/en-us/library/system.net.credentialcache.aspx,http://support.microsoft.com/kb/822456,http://blogs.msdn.com/b/buckh/archive/2004/07/28/199706.aspx(尽管这是一个“localhost”示例)。 - JaredReisinger
是的,RFC规定摘要URI应与请求匹配,但这是发送到网络的内容,而不是存储在缓存中的内容。CredentialCache.GetCredential()文档(http://msdn.microsoft.com/en-us/library/fy4394xd.aspx)指出,“GetCredential使用缓存中最长匹配的URI前缀来确定返回哪组凭据用于授权类型。”然后它显示,传递一个域将导致凭据用于该域下的*所有*资源。 - JaredReisinger
我明白了,你说得对。发送到服务器以验证单个请求的“digest-uri”与凭据缓存中存储的URI没有关系。因此,在生产代码中,可以将更高级别的URI(例如http://example.com/restrictedarea/)存储在凭据缓存中,并重用该缓存以供该路径下的所有URI使用。 - Cygon
无论如何,这不会影响问题。如果您担心的是凭据是否成功在缓存中查找,那么它们已经成功地在缓存中查找到了。并且HttpWebRequest确实尝试对我的Web服务器进行身份验证(可以在服务器日志中看到)-但是每当请求的URL附加参数时,都会使用错误的“digest-uri”。 - Cygon
显示剩余2条评论

1

在之前的回答中,大家都使用了过时的WEbREquest.Create方法。 因此,这里是我的异步解决方案,符合最近的趋势:

public async Task<string> LoadHttpPageWithDigestAuthentication(string url, string username, string password)
    {
        Uri myUri = new Uri(url);
        NetworkCredential myNetworkCredential = new NetworkCredential(username, password);
        CredentialCache myCredentialCache = new CredentialCache { { myUri, "Digest", myNetworkCredential } };
        var request = new HttpClient(new HttpClientHandler() { Credentials = myCredentialCache, PreAuthenticate = true});

        var response = await request.GetAsync(url);

        var responseStream = await response.Content.ReadAsStreamAsync();

        StreamReader responseStreamReader = new StreamReader(responseStream, Encoding.Default);

        string answer = await responseStreamReader.ReadToEndAsync();

        return answer;
    }

1

是的,可以看看我在2010年7月关于原问题的个人评论。只有当您控制服务器时才是一种选择,尽管我的应用程序必须将自身标识为MSIE,但这让我有些恼火;) - Cygon

0

我认为第二个URL指向动态页面,你应该首先使用GET调用它以获取HTML,然后再下载它。虽然我在这个领域没有经验。


抱歉,不行。网页服务器可以自由决定如何处理URL,而且第一页也可能是动态的。此外,下载的内容只有HTML,无论是下载HTML还是其他内容都没有区别。 - Cygon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接