我尝试使用 HttpWebRequest
实例对需要身份验证的 Web url 执行 POST
(ASP.NET MV3 标准 [Authorize]
装饰)具有内置会员系统的操作方法),但在 HttpWebRequest
中提供登录名和密码作为 NetworkCredentials
并没有达到目的。
我最终使用了一个全局 CookieContainer
和两个 HttpWebRequests
:
- 将请求的
CookieContainer
设置为 globalCookieContainer
。
- 将用户名和密码发布到登录 URL。 (在该步骤之后,容器仍然报告 Cookie 计数为 0)。
- 创建另一个
HttpWebRequest
实例并将 globalCookieContainer
设置为请求的 CoockieContainer
。
- 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
:
- Set a request's
CookieContainer
to globalCookieContainer
.
- POST username and password to a logon URL. (after that step the container still reports the Cookie count is 0).
- Create another
HttpWebRequest
instance and set the globalCookieContainer
to request's CoockieContainer
.
- 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?
发布评论
评论(1)
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 theAuthenticationSchemes
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 implementingIAuthenticationModule
on the server side.