In response to some discussion on Chapter 20 of the Django book, and Jacob's suggestion on django-users (here), this is a proposal for a contrib app (tentatively called django.contrib.signed_cookies) to implement signed cookies throughout a Django project.
The only setting necessary to activate it is the inclusion of the middleware class to MIDDLEWARE_CLASSES, as it uses the existing SECRET_KEY setting to help generate the signature used to authenticate the cookies. Its position in MIDDLEWARE_CLASSES matters, as it transparently handles the signature encryption, validation and signature removal, so that other middlewares and views don't need to have any knowledge of its presence.
- Each new cookie's name and value is taken along with the site's SECRET_KEY to generate a digest signature
- The signature is then prepended to the cookie's value.
- When a request comes in, it then recalculates the digest and validates it against the signature it contains.
- If the cookie doesn't contain a signature, or if it fails to validate, the cookie is removed from request.COOKIES.
- In this case, the view would usually reset the cookie, at which point it would be signed properly.
- If all succeeds, the signature is removed from the cookie's value in request.COOKIES.
Currently it uses MD5, but could easily be adapted to use a setting that would control which digest utility is used to generate the signature.