Add Secure and httpOnly Flags to Every Set-Cookie Response in Apache httpd

后端 未结 4 823
我在风中等你
我在风中等你 2021-01-30 18:20

I\'m running Apache 2.2.26:

Server version: Apache/2.2.26 (Unix)
Server built:   Jan 17 2014 12:24:49
Cpanel::Easy::Apache v3.22.30 rev9999 +cloudlinux


        
相关标签:
4条回答
  • 2021-01-30 18:44

    make sure that mod_headers.so is enabled then add the following header in apache2.conf for debian based system or httpd.conf for rpm based system

     Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    

    For lower than Apache 2.2.4 version use the following:

    Header set Set-Cookie HttpOnly;Secure 
    

    then Restart the server

    0 讨论(0)
  • 2021-01-30 18:48

    I was trying to set http, secure and samesite=strict on cookies.

    This worked for me:

    Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    

    Samesite=strict provides protection againsts XSRF.

    Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure;SameSite=strict
    

    Hope it helps.

    0 讨论(0)
  • 2021-01-30 18:49

    The Header edit directive runs before your application produces a response, so if the application is producing the header you want to edit, that header won't yet exist at the time the directive runs, and there'll be nothing for it to edit.

    You can fix this by using Header always edit (which runs after your application produces a response) instead:

    Header always edit Set-Cookie (.*) "$1; HTTPOnly"
    

    An example header, before applying the directive:

    Set-Cookie: foo=bar; domain=.example.com; path=/
    

    The same header after applying the directive:

    Set-Cookie: foo=bar; domain=.example.com; path=/; HTTPOnly
    

    I'm not sure what the directives in your question are meant to do exactly; what they actually result in when changed to Header always edit (assuming the same Set-Cookie header as in my example above) is e.g.

    Set-Cookie: f ;HTTPOnlyo=bar; domain=.example.com; path=/
    

    If you understand how regexes and backreferences work, it's obvious what's happening there, but presumably it's not what you want. The directive I've given at the top of this answer ought to work for you if, as you say, you want to add the flag to every Set-Cookie header; if your needs are more complex and I've misunderstood what you're trying to do with that search/replace, let me know.

    EDIT: In case it isn't obvious: to add both flags, you can either modify the directive like so:

    Header always edit Set-Cookie (.*) "$1; HTTPOnly; Secure"
    

    ... or use two directives:

    Header always edit Set-Cookie (.*) "$1; HTTPOnly"
    Header always edit Set-Cookie (.*) "$1; Secure"
    

    The first approach seems more sensible to me, but it's largely a matter of taste.

    0 讨论(0)
  • 2021-01-30 19:11

    This will add the tag to only those cookies that need it:

    Header always edit Set-Cookie "^((?!;\s?[Ss]ecure).)+$" "$0; Secure"
    
    0 讨论(0)
提交回复
热议问题