http://github.com/dziegler/django-urlcrypt

Chris and I just open sourced django-urlcrypt, a Django app for encrypting information in urls. The main use case for this is when you want to give a user a url that logs the user in, and redirects them to some url.

For example if I want to email users a link that logs them in and sends them to http://www.davidziegler.net/inbox/, I would send them something like http://www.davidziegler.net/r/TkNJBkNFAghDWkdFGPUAQEfcDUJfEBIREgEUFl1BQ

Some desired properties of this url are that

1. User X can’t construct a url that logs him in as User Y

2. If User X changes his password, it should invalide all of the old login ursl.

3. The url should be relatively obfuscated so it’s not totally obvious what we’re doing.

Usage

There’s more in depth examples in the README, but basically it works like this:

from django.core.urlresolvers import reverse from urlcrypt import lib as urlcrypt token = urlcrypt.generate_login_token(user, reverse('message_inbox')) encoded_url = reverse('urlcrypt_redirect', args=(token,))

Or in a template,

{% load urlcrypt_tags %} <a href="{% encoded_url user message_inbox %}"> click me to log in as {{user.username}} and go to {% url message_inbox %} </a>

Basically it uses hmac to create a hash using your SECRET_KEY from settings.py, the user’s hashed password, id, and timestamp. For details, check out urlcrypt/lib.py in the source. It’d be relatively straight forward adapt to other frameworks but I just haven’t had the need to do so yet.

I guess we could have just used public key encryption too…but pycrypto is a pain to install (EDIT: oops, I was thinking of python-mcrypt. Maybe someday we’ll implement public key encryption). Of course, crypto is hard and it’s possible that there’s some glaring security hole in there that we missed, so please let us know if you find one or send us a patch on github.

update (11/6/10): django-urlcrypt now with RSA