I use django auth for my website, which needs to have the session middleware installed.
Django session middleware always adds a session cookie, even for anonymous users (users that are not authenticated). When they authenticate the cookie is replaced by another one indicating the user is logged-in.
I want to disable the anonymous user cookie for caching purposes (varnish).
Is there a way to disable anonymous user cookies without removing session middleware which is necessary for apps using auth?
Session data is set in the cookie in the process_response
of SessionMiddleware
. This function doesn't use any setting or request.user
, so you do not have any way of knowing inside this method whether the user is a logged in user or an anonymous user. So, you can't disable sending the session cookie to the browser.
However if you want this functionality then you can subclass SessionMiddleware
and overide process_response
.
from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings
class NewSessionMiddleware(SessionMiddleware):
def process_response(self, request, response):
response = super(NewSessionMiddleware, self).process_response(request, response)
#You have access to request.user in this method
if not request.user.is_authenticated():
del response.cookies[settings.SESSION_COOKIE_NAME]
return response
And you can use your NewSessionMiddleware
in place of SessionMiddleware
.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'myapp.middleware.NewSessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With