[英]How can I do digest authentication with HttpWebRequest?
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 中刪除了參數。
你說你刪除了查詢字符串參數,但你是否嘗試一直回到主機? 我見過的每個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;
如果這樣做,您還必須確保不會多次向緩存添加相同的“權限”...對同一主機的所有請求都應該能夠使用相同的憑據緩存條目。
從這篇文章中獲取的代碼非常適合我在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);
如果網址是: http : //xyz.rss.com/folder/rss然后域名: http : //xyz.rss.com (域名部分)目錄:/文件夾/ rss(網址的其余部分)
您也可以將其作為流返回並使用XmlDocument Load()方法。
解決方案是在apache中激活此參數:
BrowserMatch "MSIE" AuthDigestEnableQueryStringHack=On
更多信息: http : //httpd.apache.org/docs/2.0/mod/mod_auth_digest.html#msie
然后在webrequest對象的代碼中添加此屬性:
request.UserAgent = "MSIE"
它對我很有用
我認為第二個URL指向動態頁面,您應首先使用GET調用它來獲取HTML然后下載它。 雖然沒有這方面的經驗。
在早期的答案中,每個人都使用過時的 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.