通过 URI 将用户名和密码传递给 .NET HttpWebRequest 不起作用
运行以下代码:
var request = HttpWebRequest.Create("http://username:[email protected]/test-http-status-codes.asp?code=401");
var response = request.GetResponse();
...并使用 Wireshark 检查请求表明我的客户端未尝试授权(该 url 是一个简单的服务,始终返回 401)。
此代码在初始质询后发送授权标头:
var request = HttpWebRequest.Create("http://username:[email protected]/test-http-status-codes.asp?code=401");
request.Credentials = new NetworkCredential("username", "password");
var response = request.GetResponse();
使用 System.Uri
类没有效果。为什么url中传递的用户名和密码没有用于身份验证?
(我知道 这篇博客文章关于在没有初始挑战的情况下传递授权标头,但这不是当前的问题)
编辑我应该补充一点,解决这个问题相当容易这个限制,对于这段代码的示例(添加 url 未转义的口味),我只是好奇为什么你必须这样做:
var userInfo = request.Address.UserInfo;
if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(':'))
{
request.Credentials = new NetworkCredential(userInfo.Split(':').First(), userInfo.Split(':').Last());
}
Running the following code:
var request = HttpWebRequest.Create("http://username:[email protected]/test-http-status-codes.asp?code=401");
var response = request.GetResponse();
... and inspecting the request using Wireshark reveals that no authorization is attempted by my client (the url is a simple service that will always return 401).
This code sends an authorization header after the initial challenge:
var request = HttpWebRequest.Create("http://username:[email protected]/test-http-status-codes.asp?code=401");
request.Credentials = new NetworkCredential("username", "password");
var response = request.GetResponse();
Using the System.Uri
class has no effect. Why is the username and password passed in the url not used for authentication?
(I'm aware of this blog post on passing the authorization header without an initial challenge, but that is not the issue at hand)
EDIT I should add that it is fairly easy to work around this limitation, for example with this bit of code (add url un-escaping to taste), I'm just curious as to why you have to do this:
var userInfo = request.Address.UserInfo;
if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(':'))
{
request.Credentials = new NetworkCredential(userInfo.Split(':').First(), userInfo.Split(':').Last());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HttpWebRequest
类不使用Uri
中的凭据(每个 dotPeek)。但是
FtpWebRequest
可以,这里是相关代码:如您所见,它只是将其附加到凭据,因此您应该使用解析的
Uri
手动执行此操作The
HttpWebRequest
class does not utilize the credentials in theUri
(per dotPeek).But the
FtpWebRequest
does, here is the relevant code:As you can see it just attaches it to credentials, so you should just do that instead manually with a parsed
Uri