Is it possible to isolate domain.ext, sub1.domain.ext and sub2.domain.ext’s cookies from one another?
I am developing a web app that is served from domain.ext. This web app uses cookie–based sessions and provides users with the ability to host a web pages containing custom JavaScript on a subdomain, ex. sub1.domain.ext, sub2.domain.ext. The subdomains do not use cookie–backed sessions.
Given this setup, is it possible to ensure the following?:
- users at sub1.domain.ext cannot read or write a cookie for domain.ext (i.e. domain.ext sessions cannot be stolen or hijacked by JavaScript embedded in a page at sub1.domain.ext).
- JavaScript embedded in a page at sub1.domain.ext cannot read or write cookies at sub2.domain.ext, and vice versa.
I’ve tested out a few things, for example it appears to be possible to interact with domain.ext’s cookies from sub1.domain.ext by running document.domain = 'domain.ext'
inside the sub1.domain.ext’s window. Is there some way to prevent this, for example by specifying some kind 开发者_如何学JAVAof policy when setting the domain from domain.ext?
You can't specify that a cookie should only be valid for example.com
by setting the domain
parameter. If you set domain=example.com
, it will be valid for *.example.com
.
Setting a cookie on example.com
without a domain
parameter sets a cookie for only example.com
in most browsers. But not IE.
So, if you ever want to have subdomains with separate cookie contexts, you should serve your site from www.example.com
only. As Gaby said, naturally you can still support access through example.com
by giving a 301 redirect to the www
version.
精彩评论