简体   繁体   中英

How can I create secure/httpOnly cookies with document.cookie?

If I create the function:

function setCookie(name, value)
    {
      // this works:
      // document.cookie=name + "=" + escape(value) + "; path=/;";
      // this does not:
      // document.cookie=name + "=" + escape(value) + "; path=/; secure; HttpOnly; SameSite=strict";
    }
setCookie('my_cookie','some_random_value');

I am not 100% on why this second option is not working. Any ideas anyone?

See MDN :

A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.

You can't set it with document.cookie because the entire point of the flag is to prevent it being set (or read) with document.cookie .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM