Code


Version 8 (modified by Simon Willison, 8 years ago) (diff)

Open ID mentioned

Multiple Authentication Backends

Currently, Django's authentication system assumes that all your users live in the db as Django models and you must use a username and password to login. This works ok until you realize that you need to support 200 users who already have Active Directory accounts (or insert your favorite windows-free LDAP server here.) In short, Django shouldn't require you to use Django models for users, and it shouldn't require you to use a username and password. What if I want to use an email address, or use some other unique key for my boss REST interface?

Zope has a pretty simple/cool solution for this. It's not really standalone, but it's not that hard to port either. Regardless of what you think of Zope, they've been doing this longer than most of us, and we could probably learn a thing or two from them. Most (meaning nearly all) of these ideas are modeled on zope.app.authentication

The details are a little flaky, and the naming kinda sucks, please make suggestions. Basically, here's how it goes:

Credentials

Instead of hard-coding checks for a cookie, or a username/password etc. etc. let's let different callables just grab the credentials from the request. In fact, let's put a bunch of these plugins in a list, so if the first one fails, we can try another.

# in settings.py
CREDENTIALS_EXTRACTORS = (
    'django.contrib.auth.SessionCredentials',
    # etc, etc.
)
class SessionCredentials:
        def __init__(self):
                self.cred_key = '_credentials'
        
        def extract_credentials(self, request):
                # get the credentials from the request and save them to the session
                # if they exist
        login = request.POST.get('login', None)
                # we probably want to go ahead and enrypt the password here since
                # we're going to store it in the session.
                password = request.POST.get('password', None)
                if login and password:
                        credentials = {'login': login, 'password': password}
                        request.session[self.cred_key] = credentials
                else:
                        credentials = request.session.get(self.cred_key, None)
                return credentials
        
        def logout(self, request):
                del self.session[self.credentials_key]

Authentication

Credendials only get us half-way there. We'd better check them against something. How about a list of authentication backends:

Add this to settings.py:

AUTHENTICATION_PLUGINS = (
    'django.contrib.auth.ModelAuthenticator',
    'django.contrib.auth.LDAPAuthenticator',
)
from django.contrib.auth.models import User

class ModelAuthenticator:
        def authenticate(self, credentials):
                from django.contrib.auth.models import User

                user = User.objects.get(username=credentials['login'])
                if user.password == credentials['password']:
                        return user
                return None

So Zope uses a factory to create a user. Your auth plugin can do whatever you feel like as long as it returns a user object. (We need to come up with a minimum informal interface for a user object. Use duck typing, not formal interfaces. The user does not need to be a django model object, but it can be. This will cause problems for permissions and groups. Eventually, those should be reworked so they aren't required to be django models either.) So if we're writing an LDAP plugin, we could make one that actually creates a Django model the first time an LDAP user successfully logs in, or we could just assemble and return a plain old python object. We could use events/factories to make this even more abstract and flexible. Let's lay the groundwork first though.

Multiple Backends

Um, so what if I want to use LDAP and Django models? Funny you should ask. By the way, this is main interface to the authentication system. You won't use credentials and authenticators directly.

class AuthUtil:
        def __init__(self):
                # XXX: these will be configurable in settings.py
                self.cred_extractors = (SessionCredentials(),)
                self.authenticators = (ModelAuthenticator(),)

        def authenticate(self, request):
                for cred_extractor in self.cred_extractors:
                        credentials = cred_extractor.extract_credentials(request)
                        for authenticator in self.authenticators:
                                user = authenticator.authenticate(credentials)
                                user.cred_extractor = cred_extractor
                                user.authenticator = authenticator
                                return user
                return None

        def logout(self, request):
                for cred_extractor in self.cred_extractors:
                        if hasattr(cred_extractor, 'logout'):
                                cred_extractor.logout(request)

Integration

How will this integrate into Django? I think either the handlers (mod_python, etc.) should start using AuthUtil, or this can be done in decorators. My vote is certainly for the first option.

Suggestions

It makes a lot of sense to store a cache of a user object as a django model, no matter what the authentication scheme, so it might very well be useful to just go ahead, reduce the Users models to its barest core, and I would add an (optional) Expiration date for automatic cache/culling (ie, always check the db first, then try everything else). (It may even be useful to add Expiration dates to permissions/groups.) I'm also thinking that many of the Credential types should just all be models in their own right with a Many-to-Many relationship with the base User class (a user could be very likely to have multiple Credentials, and there might be the occaisional need for "Group Credentials"). Once the subclassing system is in place, all of the Credential models should be subclasses of each other, probably, for good Pythonic OO-ness. Probably most DB Credentials would want Expiration dates, too. This would be a useful generic/easy system for those GET confirmation Credentials that people do. Finally, keep in mind that not all Credentials will have a username/password combo. GET Credentials will probably be some random string or hash. OpenID Credentials are URLs (tied to remote server response signatures and remote server spam white/blacklists). Making Credentials first-class models would help make it easier to remove most of the cases where a seperate User model might be necessary (ie, OpenID users could share the same base User model that Django users do, and someone can use the very same base model if they happen to use both). --Max Battcher

I agree that caching a Django user mode would generally be useful, and there should be an easy way to do it, but one shouldn't HAVE to do it. Also, if they do, they should be able to take advantage of memcached, etc. We shouldn't assume that the user is stored in the db.

To me it doesn't make sense for credentials to be stored as a model... they are just a dict or string or object or whatever that get extracted/assembled from the request. You just pass to the auth backends for checking. The auth backend already persists them. The username/password combo isn't blessed. Credentials could just as well be an api key similar to backpack, or whatever.

I think these abstractions allow for the use cases you mention, but the details certainly need to be worked out better. I explicitly want to avoid coupling this to django models, but it should easy to do so since it's most likely the default case. --Joseph Kocherhans

Here is how they approached this problem in Zope3: http://www.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/Zope3Book/principalplugin.html. You can find additional resources here: http://www.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/Zope3Book -- Linicks

I don't believe zope does things that way anymore. That first link looks to be more a step along the way than a final implementation. --Joseph Kocherhans

Open ID

Whatever solution is created for this should support the Open ID authentication model. There is already a Python module implementing most of the protocol.