c# - 如何使用 HttpWebRequest 进行摘要式身份验证?

标签 c# authentication hash httpwebrequest webrequest

各种文章(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 中删除了参数。

最佳答案

您说您删除了查询字符串参数,但您是否尝试过一直返回到主机?我见过的每个 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 进行摘要式身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172510/

相关文章:

C# 绑定(bind)对象到字符串

c# - 这是操作子类型集合的唯一 DRY 方法吗?

c# - 在 aspnet core 运行时检查托管服务器是 IIS 还是 Kestrel

ruby - 在散列中存储函数

c# - 局域网多人场景切换

java - 代号一谷歌登录问题

ios - Beta 测试、Facebook 登录、Parse。某些用户的 Facebook 信息未保存到 Parse。 swift

node.js - NodeJS : Crypto - Why do I get the same hash no matter on the input?

CSS:为什么使用 "div#container"语法而不只是 #container?

c++ - 仅使用 LogonUser() 来验证凭据