Search code examples
pythonflasksetcookie

Python Flask set_cookie domain attribute doesn't work


According to the Flask Documentation, I should be able to set a cookie with a domain path for domains besides my own like this:

resp = make_request(render_template(index.html))
resp.set_cookie('cookiekey', 'cookievalue', domain='notmydomain.example.com')

I was able to set cookies for my domain with just

resp.set_cookie('cookiekey', 'cookievalue')

and they were accepted by the browser (Chrome). However, when I try to set the domain, they don't appear in the browser. Further, testing with postman reveals that the Set-Cookie headers are sent, and are correct.

Does this mean the browser is simply ignoring my request, and if so how can I get it to accept my Set-Cookie headers?


Solution

  • TL;DR: you can't set cookies for domains completely separate from your current domain.

    Setting cookies for domains outside of your control would pose an immense security risk. The domain attribute only allows you to set cookies for either the whole domain or a subdomain. This is how, for example, a system can log you in via a subdomain such as "auth.example.org" then redirect you to "example.org".

    In practice, "unified" sign-in systems are complicated: challenges are used and data might be exchanged through a backend, not relying on the browser to properly allow other subdomains to access the original cookie.