如何使用javascript设置cookie的HttpOnly标志? [英] How do I set the HttpOnly flag of a cookie with javascript?

查看:2085
本文介绍了如何使用javascript设置cookie的HttpOnly标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个cookie,并启用HttpOnly标志。



虽然似乎有大量的资源关于如何在Java和.Net,我需要在javascript中做。



这是我的(目前失败的)函数

  createCookie = function(name,value,days){
if(days){
var date = new Date();
date.setTime(date.getTime()+(days * 24 * 60 * 60 * 1000));
var expires =; expires =+ date.toGMTString();
}
else var expires =;
document.cookie = name +=+ value + expires +; domain = my.domain.com; path = /; HttpOnly;;

感谢 -

解决方案

您无法在JavaScript中访问HttpOnly Cookie。



以下报价单是从维基百科素材


HttpOnly Cookie由大多数新型浏览器支持。在受支持的浏览器上,HttpOnly会话Cookie仅在发送HTTP(或HTTPS)请求时使用,因此限制来自其他非HTTP API(例如JavaScript)的访问


换句话说,HttpOnly Cookie只能在服务器端使用。



我在PHP中写了一个例子:

 <?php 
$ name ='foo';
$ value ='bar';
$ expirationTime = 0; //会话cookie。
$ path ='/';
$ domain ='localhost';
$ isSecure = false;
$ isHttpOnly = false;
setcookie($ name,$ value,$ expirationTime,$ path,$ domain,$ isSecure,$ isHttpOnly);
?>
< script>
alert(document.cookie);
< / script>

它警告 foo = bar p>

删除cookie,将 $ isHttpOnly 更改为 true ,重新加载网页,您会看到一个空白的快讯。但是同时浏览器存储cookie以在向服务器请求期间发送它。


I'm trying to create a cookie, with the HttpOnly flag enabled.

While there seems to be a plethora of resources about how to do it in Java and .Net, I need to do it in javascript.

Here is my (currently failing) function

createCookie = function(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";

Thanks -

解决方案

You cannot access an HttpOnly cookie in JavaScript.

The following quotation is borrowed from the Wikipedia material:

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).

In other words, HttpOnly cookies are made to be used only on the server side.

I wrote an example in PHP:

<?php
$name = 'foo';
$value = 'bar';
$expirationTime = 0;    // Session cookie.
$path = '/';
$domain = 'localhost';
$isSecure = false;
$isHttpOnly = false;
setcookie($name, $value, $expirationTime, $path, $domain, $isSecure, $isHttpOnly);
?>
<script>
alert(document.cookie);
</script>

It alerts foo=bar.

Remove the cookie, change $isHttpOnly to true, reload the page, and you'll see an empty alert. But at the same time the browser stores the cookie to send it during a request to the server.

这篇关于如何使用javascript设置cookie的HttpOnly标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆