使用客户端凭据通过 SSL 进行 HttpWebRequest

发布于 2024-07-23 12:50:56 字数 192 浏览 3 评论 0原文

我正在尝试使用 HttpWebRequest 获取需要用户名和密码的 https URI。 如果我将 URI 放入浏览器中,它会弹出一个对话框,要求提供凭据,然后就可以工作了。 使用 HttpWebRequest 给我一个 401 未经授权的错误。

NetworkCredentials 的文档说它不支持 SSL,但我找不到我应该使用的内容。

I'm trying to use HttpWebRequest to get an https URI that requires a username and password. If I put the URI into a browser it pops up a dialog asking for credentials and then works. Using HttpWebRequest gives me a 401 Unauthorized error.

The documentation for NetworkCredentials says it doesn't support SSL, but I can't find what I'm supposed to use.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遇到 2024-07-30 12:50:56

服务器使用 HTTP 基本身份验证还是其他类型? 如果使用 HTTP basic,则您可以将 Web 请求上的 Credentials 属性设置为包含正确用户名和密码的凭据,并将 PreAuthenticate 属性设置为 true。

下面是一个示例(未经测试,因此仅将其用作指南):

var uri = new Uri("https://somesite.com/something");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("myUserName","myPassword");
request.PreAuthenticate = true;

var response = request.GetResponse();

注意:根据我的经验,.NET 框架中存在一些奇怪的行为。 您可能认为它应该执行代码所说的操作,但它实际上是这样做的: 向

  • 没有凭据的服务器发送请求
  • 服务器使用
  • 您提供的凭据以 401 重新发送请求进行
  • 响应 服务器接受请求。

我不知道为什么它会这样做,因为它似乎坏了,所以也许这是我的机器的一个怪癖,也许它不会发生在你身上。

如果您的应用程序对性能不敏感,并且您的请求不是大数据的 POSTS,您可能不会注意到,但为了解决这个问题,我必须手动构建 HTTP 基本身份验证标头并将其设置在 通过操作 Headers 集合手动处理 HttpWebRequest

Is the server using HTTP basic authentication or some other kind? If it's using HTTP basic then you can set the Credentials property on the web request to a credential containing the correct username and password, and set the PreAuthenticate property to true.

Here's an example (it's untested, so use it as a guideline only):

var uri = new Uri("https://somesite.com/something");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("myUserName","myPassword");
request.PreAuthenticate = true;

var response = request.GetResponse();

Note: In my experience doing this, there is some odd behavior in the .NET framework. You'd think it should do what the code says, but it actually does this:

  • Send request to server with no credentials
  • Server responds with 401
  • Re-Send request with the credentials you gave it
  • Server accepts request.

I have no idea why it would do this, as it seems broken, so perhaps it was a quirk of my machine and maybe it won't happen to you.

If your app is not performance sensitive, and your requests aren't POSTS of large data, you probably won't notice, but to get around it, I had to manually build the HTTP basic authentication header and set it on the HttpWebRequest manually by manipulating the Headers collection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文