Secure authentication cookies with Django

Published 15th May 2008

Some time ago Alex X. Liu published a research paper on secure cookie protocols. I tried to implement the protocol in Python, but sadly had to remove some fields from the protocol. You can download it here.

Changes

This is the original protocol:

user name|expiration time|(data)k|HMAC(user name|expiration time|data|session key, k)
where k=HMAC(user name|expiration time, sk)
and sk=secret server key

I removed (data)k and session key, which changes the protocol to:

user name|expiration time|HMAC(user name|expiration time, k)
where k=HMAC(user name|expiration time, sk)
and sk=secret server key

The data field was removed because I couldn't find a good two way encryption library for Python, and the session key was removed due to the lack of SSL.

The new structure is similar to the one used for the authentication in the backend of the recently released Wordpress 2.5.

Usage

To create a cookie in Django, use the set_cookie method of the response object:

cookie = myutils.generate('arthur', 1210708139)

response = render_to_response('index.html')
response.set_cookie('mycookie', cookie)

return response