- Author:
- chrj
- Posted:
- May 7, 2010
- Language:
- Python
- Version:
- 1.1
- Tags:
- middleware sessions httponly
- Score:
- 1 (after 1 ratings)
A middleware to set the httponly flag on the 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
|
Comments
I do this by modifying the cookie path from settings.py
SESSION_COOKIE_PATH = '/;HttpOnly'
#
Please login first before commenting.