浅谈HTTP Cookie 的 Secure 和 HTTPONLY属性
最近工作中遇到了关于cookie 的secure及httponly属性的问题, 所以关注并学习了一段时间,这里做一下简要记录。关于secure和httponly标志的用途可以参考wikipedia.
Secure cookie
A secure cookie has the secure attribute enabled and is only used via HTTPS, ensuring that the cookie is always encrypted when transmitting from client to server. This makes the cookie less likely to be exposed to cookie theft via eavesdropping. HttpOnly cookie The HttpOnly cookie is supported by most modern browsers.On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other, non-HTTP APIs (such as JavaScript). This restriction mitigates but does not eliminate the threat of session cookie theft via cross-site scripting (XSS). This feature applies only to session-management cookies, and not other browser cookies.
起因: 系统PHP升级(5.1.7->5.4.5)并要求在下个升级后更新 /etc/php.ini 下的 两个变量,设定值为1.
Session.cookie_secure = 1
Session.cookie_httponly = 1
由此引发了这次调查,调查的内容涉及到了php自身cookie函数、开源框架CodeIgniter、Javascript以及JQuery对这两个属性的支持情况。
- 创建Cookie
- PHP: 5.2之前只支持secure,5.2之后添加了对httponly的支持
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] );
- CodeIgniter:在当前最新的2.1.2中只添加了对secure的支持,可是在github的CI开源项目上我发现了在下一个版本里httponly将会被添加进去。
function set_cookie($name = '', $value = '',$expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE)
- Javascript: 从这两个属性的作用就可以推测出,js对secure的支持是没问题的,可是httponly本就是为限制js而产生的,当然httponly的cookie也不会被js创建
document.cookie = "username=" +escape("leon") + "; expires=15/02/2013 00:00:00; path=/;domain=www.example.com; secure";
- Jquery: 作为js的框架,情况和js类似。
$.cookie('the_cookie', 'the_value', { expires: 7,path: '/', domain: 'x.com', secure: true });
综上可知,httponly参数只可以在服务器端设置,即通过PHP的setcookie()方法设置。所以如需添加这个属性,项目里所有对cookie的set操作都应拿到服务端进行。
- 获取Cookie
httponly参数是用来限制非HTTP协议程序接口对客户端COOKIE进行访问的,所以客户端脚本,如JS是无法取得这种COOKIE的,同时,JQuery中的“$.cookie('xxx')”方法也无法正常工作,所以想要在客户端取到httponly的COOKIE的唯一方法就是使用AJAX,将取COOKIE的操作放到服务端,接收客户端发送的ajax请求后将取值结果通过HTTP返回客户端。