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
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
I do this by modifying the cookie path from settings.py
SESSION_COOKIE_PATH = '/;HttpOnly'
#
Please login first before commenting.