【发布时间】:2011-11-07 17:52:26
【问题描述】:
我今天一直在为这个问题拔头发。我一直在开发一个内部应用程序,它执行一系列 HTTP GET 和 POST 来填写一系列网络表单。当我运行 fiddler2 时,代码运行良好——我用来调试我的 GET URI 和 POST FormData 的工具。现在我没有运行 fiddler2 我得到一个身份验证 401 错误。我会查看标题进行比较,但是如果不能运行 fiddler 会有点困难。
基本上,我的代码通过访问 URI 并存储 cookie 来工作。对站点的访问由 SSO 控制,并且由于服务器在 2003 上运行,因此它希望使用 NTLMv1。我在 Windows 7 客户端遇到的第一个问题是 Win7 会协商 128 位,而服务器只会处理 64 位并且身份验证会失败(最终 401)。使用 fiddler2 并将本地计算机上的组策略设置为 64 位,然后我就能够完成我的工作。然后我把这个软件变成了一个网络服务,今天发现有一个问题是它失败了。正如我之前所说,在 fiddler2 运行时一切正常,这给我留下了一些漏洞,因为我无法让每个客户端都安装和使用 fiddler2 来获取我的功能!
首先,我有存储 cookie 的功能……。然后我有另一个使用该 cookie 执行 get 的函数,第一个函数总是失败并显示“远程服务器返回错误:(401) 未授权。”
我希望在某个地方我错过了一些明显的事情,我不想做一些不可能的事情。
谢谢, 铝
/// <summary>
/// Function to get a cookie from a site providing the given site and credentials - this cookie then can be reused for subsequent calls
/// </summary>
/// <param name="credential">The NetworkCredential to access the site</param>
/// <param name="Uri">The Uri of the site</param>
/// <returns>A CookieContainer containing all needed cookies</returns>
private CookieContainer GetCookie(NetworkCredential credential, string Uri)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Uri);
HttpWebResponse resp;
CookieContainer cookieJar = new CookieContainer();
req.AllowAutoRedirect = true;
req.Credentials = credential;
req.CookieContainer = cookieJar;
resp = (HttpWebResponse)req.GetResponse(); // This line always fails with: The remote server returned an error: (401) Unauthorized.
return cookieJar;
}
/// <summary>
/// Function to perform a HTTP GET
/// </summary>
/// <param name="cookieJar">A CookieContainer for keeping the reference of our sessions</param>
/// <param name="credential">The Credentials to use to access the site</param>
/// <param name="Uri">The Uri to GET</param>
private void DoGet(CookieContainer cookieJar, NetworkCredential credential, string Uri)
{
HttpWebRequest req;
HttpWebResponse resp;
// Just grab the site uri where the cookie is stored
string[] UriParts = Uri.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
Uri CookieUri = new Uri(UriParts[0] + "//" + UriParts[1]);
// Use cookie information to get first page of call entry
req = (HttpWebRequest)HttpWebRequest.Create(Uri);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookieJar.GetCookies(CookieUri)[0]);
req.AllowAutoRedirect = true;
req.Credentials = credential;
req.CookieContainer = cookieJar;
resp = (HttpWebResponse)req.GetResponse();
}
【问题讨论】:
-
你试过用 Wireshark 运行吗?它将充当数据包捕获,但不是代理。它应该让您看到 NTLM 协商而不干扰它。 (它在解码 NTLMSSP 标头方面也做得很好。)