Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Compact Privacy Policy with Django

How do I set a P3P compact privacy policy from Django so that IE accepts cookies from my site when the security settings are on HIGH - i.e. no cookies accepted unless there's a Compact Privacy Policy.

Cheers Guy

like image 953
Guy Bowden Avatar asked Nov 19 '09 18:11

Guy Bowden


1 Answers

Middleware is the preferred way to do things like this on an "every request" basis. For instance, here is a simple bit of middleware to add the same (example) P3P header to every response Django generates:

In settings.py:

P3P_COMPACT = 'policyref="http://www.example.com/p3p.xml", CP="NON DSP COR CURa TIA"'
MIDDLEWARE_CLASSES += ('myapp.middleware.P3PHeaderMiddleware',)

In myapp/middleware.py:

from django.conf import settings

class P3PHeaderMiddleware(object):
    def process_response(self, request, response):
        response['P3P'] = getattr(settings, 'P3P_COMPACT', None)
        return response

You could also get a similar effect in a single view by setting the P3P header in the response:

def my_view(request):
    response = render_to_response('my_template.html')
    response['P3P'] = 'CP="NON DSP COR CURa TIA"'
    return response

To expand on the topic a little bit, cookies and headers such as the P3P header are both sent at the same time, as part of the response; in fact, under the hood, cookies are set with another response header. You can see the cookie header using curl:

$ curl --head http://www.google.com/
HTTP/1.1 200 OK
Date: Wed, 13 Jan 2010 00:04:59 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=d2c09762c479f94e:TM=1263341099:LM=1263341099:S=oJby3NpU4RsRfuYa; expires=Fri, 13-Jan-2012 00:04:59 GMT; path=/; domain=.google.com
Set-Cookie: NID=30=kdKrd5e-u6Xs7cUe3p4eaNDtv6SO88uBL5v6_M1XMTSRmkh7okxrWLOm-l_uZdN37PxQIe4dBlekFFVCpTFXGyIDlUrz1hEwhgVLvXfIik_VeVWGmWzKbA5qu_Zq0sOi; expires=Thu, 15-Jul-2010 00:04:59 GMT; path=/; domain=.google.com; HttpOnly
Server: gws
X-XSS-Protection: 0
Transfer-Encoding: chunked
like image 192
JdV Avatar answered Oct 23 '22 20:10

JdV