0

i want to create cookie based authentication depends on path , so simply for testing i have create two views and set cookies respectively

View 1 Cookie With globalLy available enter image description here View 2 Cookie With Specific

enter image description here

But the problem in both view only global cookie is available

View 1 enter image description here

View 2 enter image description here

You can see both cookie have same name but different path, but when we get cookies only global cookie is available

if i display request.META.get('HTTP_COOKIE')) then all cookie are display but not in request.COOKIES.get('last_visit')

enter image description here

please help, i have tested in php , it works fine but not in python django

Faisal
  • 152
  • 1
  • 1
  • 12

1 Answers1

2

The problem that you face relates partly to Django, but firstly to the properties of HTTP cookies mechanism itself.

A cookie valid for a path is also valid for all its subpaths (a query string doesn't matter). So last_visit cookie intended for / is also valid for /view2/. For specifics of the matching mechanism, defining whether a cookie is suitable for a path, see subsection "5.1.4. Paths and Path-Match" in RFC6265.

So both cookies are sent, and the order in which they are listed in Cookie: HTTP header is from more specific paths to less specifics ones. See over here in RFC6265.

Now, Django processes cookies from the header one by one and populates a plain python dictionary request.COOKIES, rewriting values when keys are already present. That is how your value for last_visit is rewriten when both cookies for both paths are sent in http request.

While Django processes cookies like that, though it would be more reasonable to only keep the first (not the last) value for the key as it relates to more specific path, you can fix the issue by only using the same cookie names for paths of the same level -- for /root/view1/ and /root/view2/, but not for /root/. Or You can divert cookie names with respect to http path like that:

import hashlib
cookie_name = 'last_visit%s' % hashlib.md5(request.path).hexdigest()
# ...
cookie = request.COOKIES.get(cookie_name)
# ...
response.set_cookie(cookie_name, cookie, path=request.path)
Community
  • 1
  • 1
user2683246
  • 3,399
  • 29
  • 31