I have saved my session cookies with secure flag set. As the browser will be sending the cookies with every XHR, I can see that the cookies which are being sent are not having the security=secure flag set. How can I ensure that while sending the XHR, the cookies are also sent with secure flag? (i.e. security=secure)
1 Answer
I can see that the cookies which are being sent are not having the security=secure flag set
That is correct. The cookie specification requires that clients send only the cookie value in the Cookie: header, and not the metadata (secure, domain, etc). This is true for all HTTP requests, XHR or otherwise.
A shortcoming of this design is that you can't tell from the server side where a cookie was originally set. A cookie coming to you on https://www.example.com/ might actually have been set from http://www.example.com/ but without the secure flag. It could also have come from http://other-subdomain.example.com/, setting the domain to example.com. There is no way to know.
About all you can do to mitigate the possibility of a man-in-the-middle attacker using an unprotected connection to http://www.example.com/ to inject cookies into https://www.example.com/ is to use https: exclusively. On the http port instead serve a redirect to https: and set an HTTP Strict Transport Security header to try to prevent browsers from connecting to the http: address in future.
secureare set in the response header that set the cookie. To send it with requests would make no sense.