Disable anonymous user cookie with Django

前端 未结 1 1606
感动是毒
感动是毒 2021-01-02 07:32

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 us

相关标签:
1条回答
  • 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',
    )
    
    0 讨论(0)
提交回复
热议问题