Implementing Django Auth Back Ends

August 3, 2010

Here's some Django code to implement an auth backend using a web service for authentication. This relies on memcached to store the user details, and doesn't need a backend database to store anything.

The code behind LoginSessionObject.login() will perform the web service call, and it returns a security token which is then required to be passed to all subsequent web services. We store this in the user object's id field.

from django.contrib.auth.models import User
from django.conf import settings
import memcache

class CustomAuthentication:
    def authenticate(self, username=None, password=None, request=None):
      try:
          lLoginSession = LoginSessionObject()        
          lLoginSession.Login(username,password)  
          lUser = CustomUser(username=username, password=password)
          lUser.is_staff = True
          lUser.is_superuser = False
          lUser.is_active = True
          lUser.id=lLoginSession.SecurityToken
          request.session['LoginSession'] = lLoginSession
          lMemcached=memcache.Client([settings.CACHE_BACKEND_ADDRESS])
          lMemcached.set(user.id,user);
          return lUser
      except Exception:
          return None

    def get_user(self, user_id):
        lMemcached=memcache.Client([settings.CACHE_BACKEND_ADDRESS])
        lUser=lMemcached.get(user_id);
        return lUser

class CustomUser (User):
    def save(self):
        """
        disable saving users to database
        """
        pass

To install, set AUTHENTICATION_BACKENDS in your settings file:

AUTHENTICATION_BACKENDS = (
    'path.to.CustomAuthentication',
 )

Tags: django auth backend