何时应使用 HttpWebRequest.Credentials

发布于 2024-12-26 12:46:15 字数 764 浏览 3 评论 0 原文

我尝试使用 HttpWebRequest 实例对需要身份验证的 Web url 执行 POST(ASP.NET MV3 标准 [Authorize] 装饰)具有内置会员系统的操作方法),但在 HttpWebRequest 中提供登录名和密码作为 NetworkCredentials 并没有达到目的。

我最终使用了一个全局 CookieContainer 和两个 HttpWebRequests

  1. 将请求的 CookieContainer 设置为 globalCookieContainer
  2. 将用户名和密码发布到登录 URL。 (在该步骤之后,容器仍然报告 Cookie 计数为 0)。
  3. 创建另一个 HttpWebRequest 实例并将 globalCookieContainer 设置为请求的 CoockieContainer
  4. POST 到需要身份验证的最终 URL。由于某种原因,这次第二个请求对象提供了 cookie 作为请求的一部分,并且它通过了。

cookie 管理的整个“魔力”没有在任何地方得到很好的描述(我真的尝试过搜索)。

我们已经涵盖了这种情况。但在什么情况下应该使用 HttpWebRequest.Credentials 呢?

I tried to perform a POST using a HttpWebRequest instance to a web url that requires an authentication (an ASP.NET MV3 standart [Authorize] decorated action method with build-in membership system), but providing login and passowrd as NetworkCredentials in HttpWebRequest didn't do the trick.

I ended up using a global CookieContainer and two HttpWebRequests:

  1. Set a request's CookieContainer to globalCookieContainer.
  2. POST username and password to a logon URL. (after that step the container still reports the Cookie count is 0).
  3. Create another HttpWebRequest instance and set the globalCookieContainer to request's CoockieContainer.
  4. POST to a final url that requires authentication. For some reason, this time second request object provides the cookies as a part of a request and it goes through.

An entire "magic" of cookie management isn't discribed anywhere well (I really tried to search around).

We've got this scenario covered. But in what cases HttpWebRequest.Credentials should be used?

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

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

发布评论

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

评论(1

━╋う一瞬間旳綻放 2025-01-02 12:46:15

HttpWebRequest.Credentials 旨在通过 AuthenticationSchemes 枚举。其中包括基本和摘要式 HTTP 身份验证、NTLM 和 Kerberos。

也就是说,您可以通过从客户端的 NetworkCredential 派生并实现 IAuthenticationModule 在服务器端。

HttpWebRequest.Credentials is meant to be used when the authentication is performed through one of the schemes in the AuthenticationSchemes enum. Among others, this includes Basic and Digest HTTP auth, NTLM and Kerberos.

That said, you can cook up your own custom authentication schemes by deriving from NetworkCredential on the client side and implementing IAuthenticationModule on the server side.

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