最近工作中遇到了关于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对这两个属性的支持情况。
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] );
function set_cookie($name = '', $value = '',$expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE)
document.cookie = "username=" +escape("leon") + "; expires=15/02/2013 00:00:00; path=/;domain=www.example.com; secure";
$.cookie('the_cookie', 'the_value', { expires: 7,path: '/', domain: 'x.com', secure: true });
综上可知,httponly参数只可以在服务器端设置,即通过PHP的setcookie()方法设置。所以如需添加这个属性,项目里所有对cookie的set操作都应拿到服务端进行。
httponly参数是用来限制非HTTP协议程序接口对客户端COOKIE进行访问的,所以客户端脚本,如JS是无法取得这种COOKIE的,同时,JQuery中的“$.cookie('xxx')”方法也无法正常工作,所以想要在客户端取到httponly的COOKIE的唯一方法就是使用AJAX,将取COOKIE的操作放到服务端,接收客户端发送的ajax请求后将取值结果通过HTTP返回客户端。