Code


Version 10 (modified by jkocherhans, 8 years ago) (diff)

much much simpler

Multiple Authentication Backends

See http://code.djangoproject.com/ticket/1428 for the current patch that implements this.

Authentication

The default authentication mechanism for Django will still check a username/password against django.contrib.auth.models.User

The path to the default authentication backend can be set in settings.py via the AUTHENTICATION_BACKEND variable. This variable is used by django.contrib.auth.middleware.AuthenticationMiddleware to set the request.user attribute.

Backends

Authentication backends are pretty simple. They just need to implement 2 methods, authenticate and get_user.

backend.authenticate(self, request)

backend.authenticate takes a request object, and if it finds valid credentials in the request, it returns a user object. If not, it returns None.

Note that when you write an authentication backend, you can grab a token, or whatever else you want out of the request, and check against ldap, another sql database, or pretty much anything accessible via python.

The user object will generally be an instance of django.contrib.auth.models.User, but really, it could be anything. You will need to at least fake the interface for django.contrib.auth.models.User if you want to use the admin system however. Your backend can create and save an instance of django.contrib.auth.models.User when a user logs in for the first time. You could also add them to a default set of groups at that time.

backend.get_user(self, user_id)

backend.get_user simply takes a user id and returns the user that matches that id.

Authenticating

Here's a very simple code sample that authenticates a user:

from django.conf import settings
from django.contrib.auth.backends import load_backend

def myview(self, request):
    backend = load_backend(settings.AUTHENTICATION_BACKEND)
    user = backend.authenticate(request)
    if user is None:
        # do whatever for invalid logins
    else:
        # the user is valid, persist their id in a session var or whatever.
        # do whatever else this view is suppose to do.

Note that the view is in charge of "logging in" a user, that is, the view must persist the id of the user somehow. A session variable is the easiest place, but a signed cookie would be desireable for those who don't want to use the session middleware. It would be nice if this were more convenient. It shouldn't be hard to do.

For extra points, there should be ways of tying this all in with WSGI ;)

Using Multiple Backends

To use multiple authentication backends, you just use another backend called django.contrib.auth.backends.MultiBackend It is configured with a list of backends you'd like to use, and just calls each backend in order.