Django gotcha with custom Authentication backends

I just came across a pretty annoying issue with using custom authentication backends in Django. Here’s a quick little note about the authentication system that could save you some time, if you ever come across the same issue.

If you need to perform any sort of application specific authentication, you can accomplish this by writing your own backend and pointing to it in your settings module:

AUTHENTICATION_BACKENDS  = ('my_app.MyAuthBackend',)

The problem occurred when I changed that to a different custom backend:

AUTHENTICATION_BACKENDS  = ('my_other_app.MyOtherAuthBackend',)

I was getting a 500 error that complained it couldn’t import my_app.MyAuthBackend, which was extremely puzzling because all code that would’ve referenced that module had been removed. I confirmed this by searching the entire filesystem with grep to try and find the rogue line of code that (I assumed) still contained a reference to that now-removed module. Not a single file on the filesystem contained the string “MyAuthBackend”. Confusion++.

I rebooted the server and removed all .pyc files — still not working. I even fired up the console to check the settings object, and it confirmed that AUTHENTICATION_BACKENDS had indeed been updated to the new setting, and should not have been importing the old setting.

After cracking open Django’s source I quickly discovered the problem: authentication backend paths are stored in a Session once a User logs in. This is why I couldn’t find any code referencing the old backend – it was stored in the database!

Here are the relevant lines from get_user() in django.contrib.auth.init.py

backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)

Very confusing. You’d think that updating the settings would, you know, change the settings of your application. I hadn’t considered that the database would store references to old settings like that. At the very least the documentation should be updated to explain the possible gotcha. Maybe I’ll do it myself if I get a chance after work…


2 Comments

Alex

August 20, 2010

thanks

Alex

August 20, 2010

thanks

Leave a comment

Comments

Me going grey

Kyle Fox is a developer and designer currently located in Edmonton, Alberta, Canada. (more)