【问题标题】:Writing cookies from CookieContainer to the IE cookie store将 Cookie 从 CookieContainer 写入 IE cookie 存储
【发布时间】:2011-04-09 18:20:07
【问题描述】:

我想从桌面应用导航到网络应用中的页面。 “没问题”,我听到你说,“只需使用正确的 URL 启动默认浏览器”。但是,Web 应用程序使用 ASP.NET 表单身份验证,用户不想看到登录页面,因为他们已经在桌面应用程序中使用相同的凭据进行了身份验证。

这听起来很简单,我所要做的就是从桌面应用程序发出一个 HTTP POST,它会伪造来自 Web 应用程序登录页面的回发。然后,Web 应用程序将设置其身份验证票证和会话状态 cookie,将它们返回给我,我会将它们存储在 IE cookie 存储中。然后我可以导航到所需的页面,网络应用程序会认为它已经过身份验证。

我有一些工作代码构建 HTTP POST,将其发送出去,并获得包含正确 cookie 的有效响应。但是,我看不到如何将它们写入 IE cookie 存储。谁能指出我正确的方向?

示例代码:

var requestUrl = Properties.Settings.Default.WebsiteLoginPageUrl;

var requestEncoding = Encoding.GetEncoding(1252);

// Simulated login postdata
var requestText = string.Format(
    "__VIEWSTATE={2}&__EVENTTARGET={3}&__EVENTARGUMENT={4}&__EVENTVALIDATION={5}&userNameText={0}&passwordText={1}&submitButton=Log+In",
    HttpUtility.UrlEncode(Properties.Settings.Default.UserName),
    HttpUtility.UrlEncode(Properties.Settings.Default.Password),
    Properties.Settings.Default.FakeViewState,
    Properties.Settings.Default.FakeEventTarget,
    Properties.Settings.Default.FakeEventArgument,
    Properties.Settings.Default.FakeEventValidation);

var request = (HttpWebRequest) WebRequest.Create(requestUrl);
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestEncoding.GetByteCount(requestText);
request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
request.AllowAutoRedirect = false;
request.KeepAlive = false;
request.CookieContainer = new CookieContainer();

using(var writer = new StreamWriter(request.GetRequestStream(), requestEncoding)) {
    writer.Write(requestText);
}

var response = (HttpWebResponse) request.GetResponse();

// TODO: Grab the response cookies and save them to the interactive desktop user's cookie store.

Process.Start(new ProcessStartInfo {
    FileName = Properties.Settings.Default.WebsiteTargetPageUrl,
    UseShellExecute = true,
});

【问题讨论】:

    标签: c# .net internet-explorer httpwebresponse cookiecontainer


    【解决方案1】:

    您需要调用非托管InternetSetCookie() 函数。看!有人wrote the interop 已经为您服务了。不过你应该验证它的正确性。

    【讨论】:

    • 感谢 Jeff,这正是我所需要的。现在只需要弄清楚如何将 .NET cookie 属性转换为正确的格式。 :-)
    • 在已知 cookie 上调用 InternetGetCookie 并查看它的样子。
    • 它包含有趣的数据,这些数据并不直接对应于 .NET Cookie 对象的所有属性。我目前正在对格式进行逆向工程,我会告诉你的。
    • Jeff,抱歉耽搁了,这个开发任务现在被搁置了,我还没有时间完成概念验证。但是,我已将您的答案标记为正确,因为我可以看到这是正确的方法。感谢您的帮助。
    • @Christian:你做过逆向工程吗?我发现自己现在(几乎)在同一个地方。
    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多