Because the middleware logic reads the domain directly from settings, the
result is a largely copy-pasted method just to change the domain being set
on the cookie. This override is also liable to break if the middleware or
settings change in future Django releases.
In contrast, `SecurityMiddleware` was much easier to override, since any
settings are loaded as instance attributes in `__init__`.
The proposed solution would consist of loading settings in the session
middleware `__init__` e.g. `self.cookie_domain =
settings.SESSION_COOKIE_DOMAIN`.
Happy to submit a PR if this seems reasonable.
--
Ticket URL: <https://code.djangoproject.com/ticket/34073>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* cc: Adam Johnson (added)
* stage: Unreviewed => Accepted
Comment:
Sounds reasonable.
--
Ticket URL: <https://code.djangoproject.com/ticket/34073#comment:1>
* status: new => closed
* resolution: => wontfix
Comment:
Copying from settings in `__init__` will mean that tests using
`override_settings` to replace the values will no longer work.
You can manipulate the domain of a cookie after it's set:
{{{
In [11]: from django.http import HttpResponse
In [12]: r = HttpResponse()
In [13]: r.set_cookie("session", "123", domain="example.com")
In [14]: r.cookies["session"]["domain"] = "example.org"
}}}
Cookies in `response.cookies` are `http.cookies.Morsel` objects:
https://docs.python.org/3.10/library/http.cookies.html#http.cookies.Morsel
So you can subclass the existing middleware and override
`process_response` to call `super()`, then manipulate the cookie before
returning the response.
--
Ticket URL: <https://code.djangoproject.com/ticket/34073#comment:2>
* stage: Accepted => Unreviewed
--
Ticket URL: <https://code.djangoproject.com/ticket/34073#comment:3>
Comment (by Michael Gisi):
Replying to [comment:2 Adam Johnson]:
Got it, I hadn't considered the effect on tests or the ability to modify
cookies after calling `set_cookie`. Thank you for your detailed response,
cheers.
--
Ticket URL: <https://code.djangoproject.com/ticket/34073#comment:4>