Django Authentication Backends

August 18, 2010 No comments yet

If you are building a Django frontend for a legacy application chances are you will need to integrate your existing user database table(s) with the the Django authentication system (django.contrib.auth). In this tutorial we will look at writing our own authentication backend and plugging it into django.contrib.auth.

Getting Started

Authentication backends are pure python classes. Given a username and password, they are expected to validate them against an authentication source (such as a database) and return a User object. There is no requirement as to where the class is placed, however I always put it in the same directory as the application that handles registrations and logging in.
When a user logs in, Django will check the AUTHENTICATION_BACKENDS (tuple) setting and iterate through all backends until one returns true. The default authentication backend is django.contrib.auth.backends.ModelBackend.

Writing Our Backend

Our backend must have two methods: authenticate and get_user

authenticate takes two arguments – username and password. It is expected to return a User instance or None. The authenticate method should check the given username and password against the user table of the legacy application. If the credentials match, then create a new User instance, save it, and return it. If…


Categories