How to set cookie secure flag using javascript

前端 未结 3 1530
慢半拍i
慢半拍i 2020-12-30 18:40

I have tried to set a cookie using document.cookie = \"tagname = test; secure\" but this does not set the secure flag. Am I setting it wrong? Can you only set i

相关标签:
3条回答
  • 2020-12-30 19:00

    because the flag is called secure, not security:

    document.cookie = "tagname = test;secure";
    
    0 讨论(0)
  • 2020-12-30 19:01

    This cookie package is easy to use @ https://www.npmjs.com/package/js-cookie

     //to set cookie use
     Cookies.set('name', 'value', { expires: 7, path: '' });
    
     //to read the cookie, use
     Cookies.get('name'); // => 'value'
    
     //to delete cookie this
     Cookies.remove('name')
    
      //to set secure cookie this
     Cookies.set('name', 'value', { secure: true });
    
    0 讨论(0)
  • 2020-12-30 19:10

    TL:DR

    document.cookie = "tagname = test;secure";
    

    You have to use HTTPS to set a secure attribute

    The normal (or formal, maybe) name is attribute. Since the flag refers to other things.

    More Info

    Cookie attributes:

    Secure - Cookie will be sent in HTTPS transmission only.

    HttpOnly- Don't allow scripts to access cookie. You can set both of the Secure and HttpOnly.

    Domain- specify the hosts to which the cookie will be sent.

    Path - create scopes, cookie will be sent only if the path matches.

    Expires - indicates the maximum lifetime of the cookie.

    More details and practical usages. Check Testing_for_cookies_attributes_(OTG-SESS-002)

    UPDATES The following contents expire in June 2, 2016.

    Cookie Flags

    Cookie flags are prefixes. At the moment, they are described in the RFC draft as a update to the RFC6265

    These flags are used with the 'secure' attribute.

    __Secure-
    

    The dash is a part of the prefix. This flag tells the browser, the cookie should only be included in 'https'.

    __Host-
    

    A cookie with this flag

    1. must not have 'domain' attribute, it will be only sent to the host which set it.

    2. Must have a 'path' attribute, that is set to '/', because it will be sent to the host in every request from the host.

    0 讨论(0)
提交回复
热议问题