19

我发现的各种文章(1、2 使这看起来很容易:

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 参数——但是从传递给的 URL 中删除参数credentialCache.Add()并没有改变任何事情。所以它一定是相反的,.NET 框架中的某个地方错误地从 URL 中删除了参数。

4

4 回答 4

8

您说您删除了查询字符串参数,但是您是否尝试一直回到主机?我见过的每个 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;

如果这可行,您还必须确保不会多次将相同的“权限”添加到缓存中......对同一主机的所有请求都应该能够使用相同的凭据缓存条目。

于 2010-07-21T00:12:03.943 回答
6

从这篇文章中获取的代码对我来说非常有效通过 C# 中的 HttpWebRequest 实现摘要身份验证

我遇到了以下问题,当我在浏览器中浏览提要 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();
    }
}

}

第 2 步:调用新方法

DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);

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

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

于 2015-06-16T16:58:29.757 回答
1

解决办法是在apache中激活这个参数:

    BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On 


更多信息:http ://httpd.apache.org/docs/2.0/mod/mod_auth_digest.html#msie

然后在您的代码中为 webrequest 对象添加此属性:

    request.UserAgent = "MSIE"

它对我很有效

于 2012-01-04T20:10:44.797 回答
0

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

于 2010-07-18T20:47:06.690 回答