如何使用 HttpWebRequest 进行摘要式身份验证? [英] How can I do digest authentication with HttpWebRequest?

查看:42
本文介绍了如何使用 HttpWebRequest 进行摘要式身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

各种文章(12) 我发现让这看起来很容易:

Various articles (1, 2) I discovered make this look easy enough:

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,结果是服务器日志(运行 Apache 2.2)中的 400 Bad Request 消息:

However, this only works for URLs without URL parameters. For example, I can download http://example.com/test/xyz.html just fine, but when I attempt to download http://example.com/test?page=xyz, the result is a 400 Bad Request message with the following in the server's logs (running Apache 2.2):

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

我的第一个想法是摘要规范要求从摘要哈希中删除 URL 参数——但是从传递给 credentialCache.Add() 的 URL 中删除参数并没有改变任何事情.所以它一定是相反的,.NET 框架中的某个地方错误地从 URL 中删除了参数.

My first idea was that the digest specification requires URL parameters to be removed from the digest hash -- but removing the parameter from the URL passed to credentialCache.Add() didn't change a thing. So it must be the other way around and somewhere in the .NET framework is wrongly removing the parameter from the URL.

推荐答案

您说您删除了查询字符串参数,但您是否尝试过完全回到主机?我见过的 CredentialsCache.Add() 的每个示例似乎都只使用主机,以及 CredentialsCache.Add() 将 Uri 参数列为uriPrefix",这似乎很有说服力.

You said you removed the querystring paramters, but did you try going all the way back to just the host? Every single example of CredentialsCache.Add() I've seen seems to use only the host, and the docs for CredentialsCache.Add() list the Uri parameter as "uriPrefix", which seems telling.

换句话说,试试这个:

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;

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

If this works, you will also have to make sure that you don't add the same "authority" to the cache more than once... all requests to the same host should be able to make use of the same credential cache entry.

这篇关于如何使用 HttpWebRequest 进行摘要式身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆