当WFP遇到HttpOnly

今天用wpf写一个简单的程序,用到Frame来切换网页和本地页面,这个时候希望网页切换到本地页面后再切换网页时必须要重登录,然而服务器发送的Cookies却是HttpOnly的。

HttpOnly的cookies作用是为了提高站点安全性防止跨站攻击,所以客户端对他的访问有很大的限制。更多信息请参考Mitigating Cross-site Scripting With HTTP-only Cookies

搜索了不少资料,也尝试了用mshtml.HTMLDocument2接口获取Frame中的WebBrowser对象的Document属性里面的cookie,然后发现是null。搜索到的资料里面提到

However it is not good enough as looks like MSHTML.Document2 – does not allow to extract important HttpOnly cookies (like ASP.Net_SessionID) – and I need manually construct CookiesCollection object from Cookies string.

这样不得不放弃直接修改Cookies的方法。最后找到一篇文章提到

To clear session (such as HttpOnly cookies), you can use InternetSetOption() from wininet.dll.

private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
 
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

and use this method whenever need to clear session.

InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
webBrowser1.Document.Window.Navigate(url);

还好我只是需要清除Cookies结束当前的session就可以了,上面这个API刚好能完成我要的功能。
 

后来还看到一篇文章Retrieve HttpOnly Session Cookie in WebBrowser – CodeProject,上面提到

Now, we can inject into every request, including AJAX requests. How to get/set the HTTP-Only cookies when a request is being sent? There is a new added flag INTERNET_COOKIE_HTTPONLY in IE8 SDK for InternetGetCookieEx / InternetSetCookieEx.

如果系统浏览器是IE8以上的版本可以使用这两个API来获取和设置HttpOnly的Cookies。

此条目发表在分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据