Middleware for using HttpOnly session cookie (including monkey patching for support for Python <2.6)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import Cookie

class HttpOnlySessionCookie(object):

    def process_response(self, request, response):

        # Monkey patch the Cookie.Morsel class if needed

        if "httponly" not in Cookie.Morsel._reserved:

            Cookie.Morsel._reserved["httponly"] = "httponly"

            def output_string(self, attrs=None):

                result = []
                RA = result.append

                RA("%s=%s" % (self.key, self.coded_value))

                if attrs is None:
                    attrs = self._reserved

                items = self.items()
                items.sort()

                for K,V in items:
                    if V == "": continue
                    if K not in attrs: continue
                    if K == "expires" and type(V) == type(1):
                        RA("%s=%s" % (self._reserved[K], _getdate(V)))
                    elif K == "max-age" and type(V) == type(1):
                        RA("%s=%d" % (self._reserved[K], V))
                    elif K == "secure":
                        RA(str(self._reserved[K]))
                    elif K == "httponly":
                        RA(str(self._reserved[K]))
                    else:
                        RA("%s=%s" % (self._reserved[K], V))

                return Cookie._semispacejoin(result)

            Cookie.Morsel.OutputString = output_string
            
        if response.cookies.has_key(settings.SESSION_COOKIE_NAME):
            response.cookies[settings.SESSION_COOKIE_NAME]['httponly'] = True

        return response

More like this

  1. Sessions and authentication without cookies by danfairs 6 years, 5 months ago
  2. CurrentSessionIDMiddleware by troolee 3 years, 8 months ago
  3. Add httponly to session cookie by rodolfo.3 4 years ago
  4. apache authentication via cookies by sean 7 years, 1 month ago
  5. Strip Google Analytics cookies for caching middleware purposes by nf 4 years, 5 months ago

Comments

cootetom (on May 7, 2010):

I do this by modifying the cookie path from settings.py

SESSION_COOKIE_PATH = '/;HttpOnly'

#

(Forgotten your password?)