Ticket #689: remote_user.diff

File remote_user.diff, 6.2 KB (added by Koen Biermans <koen.biermans@…>, 17 years ago)

patch using both middleware and authentication backend (doc included)

  • django/contrib/auth/backends.py

     
    1919            return User.objects.get(pk=user_id)
    2020        except User.DoesNotExist:
    2121            return None
     22
     23class RemoteUserAuthBackend(ModelBackend):
     24    def authenticate(self, username, password=None):
     25        """
     26        Authenticate user - RemoteUserAuth middleware passes REMOTE_USER
     27        as username. password param is not used, just added in case :)
     28        """
     29        user = None
     30        if username:
     31            try:
     32                user = User.objects.get(username=username)
     33            except User.DoesNotExist:
     34                # Auto-create user
     35                if settings.REMOTE_USER_AUTH_AUTO_CREATE:
     36                    # We'll create a password, but it won't be used
     37                    password = User.objects.make_random_password()
     38                    user = User.objects.create_user(username, '', password)
     39                    user.is_staff = False
     40                    user.save()
     41                    # Check if there is an after_create function set in settings
     42                    # it is a string like 'path.to.module.function'
     43                    try:
     44                        path = settings.REMOTE_USER_AUTH_AFTER_CREATE
     45                    except:
     46                        # No custom after_create function
     47                        return user
     48                    i = path.rfind('.')
     49                    module, attr = path[:i], path[i+1:]
     50                    try:
     51                        module = __import__(module, {}, {}, [attr])
     52                    except ImportError:
     53                        raise ImproperlyConfigured, 'Error importing function %s' % path
     54                    try:
     55                        func = getattr(module, attr)
     56                        # this function is called with the new User object
     57                        func(user)
     58                    except:
     59                        raise ImproperlyConfigured, 'Error executing function %s' % path
     60        return user
  • django/contrib/auth/middleware.py

     
    1010        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
    1111        request.__class__.user = LazyUser()
    1212        return None
     13
     14class RemoteUserAuthMiddleware(object):
     15    def process_request(self, request):
     16        from django.contrib.auth import authenticate, login
     17        # AuthenticationMiddleware is required to create request.user
     18        error = """The Django RemoteUserAuth middleware requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES
     19setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' *before* the RemoteUserMiddleware class."""
     20        assert hasattr(request, 'user'), error
     21        if request.user.is_anonymous():
     22            try:
     23                user = authenticate(username=request.META['REMOTE_USER'])
     24            except:
     25                user = None
     26            if user is not None:
     27                request.user = user    # set request.user to the authenticated user
     28                login(request, user)   # auto-login the user to Django
     29        return None
     30 No newline at end of file
  • docs/auth_remote_user.txt

     
     1=============================
     2Authenticating against REMOTE_USER from Apache
     3=============================
     4
     5Typically on an intranet, users are already authenticated (e.g. in a Windows domain).
     6It is possible to let Apache use NTLM to verify that a user is authenticated, and only
     7allow valid users to enter your website. Apache will set a REMOTE_USER variable containing
     8the user's username. This can be used to inform django which user is accessing the site.
     9If the user is not yet in django's userbase, she can be added automatically.
     10
     11Configuring Apache
     12==============
     13
     14You will need a module that can authenticate using NTLM.
     15Examples are mod_NTLM or mod_auth_sspi.
     16Configure Apache to use these to authenticate the user.
     17An example configuration using mod_auth_sspi looks like this:
     18
     19# Add the module:
     20
     21LoadModule sspi_auth_module modules/mod_auth_sspi.so
     22
     23# Configure the authentication:
     24
     25    <Location /example/>
     26        AuthName "myIntranet"
     27        AuthType SSPI
     28        SSPIAuth On
     29        SSPIAuthoritative On
     30        SSPIDomain "myDomain"
     31        SSPIOmitDomain On
     32        SSPIUsernameCase "upper"
     33       
     34        Require valid-user
     35
     36        SetHandler python-program
     37        PythonHandler django.core.handlers.modpython
     38        SetEnv DJANGO_SETTINGS_MODULE your_settings
     39        PythonPath "['d:\\\\websites'] + ['d:\\\\websites\\\\myproject'] + sys.path"
     40    </Location>
     41
     42Configuring django
     43=============
     44
     45In your settings file, add the RemoteUserAuthMiddleware and the RemoteUserAuthBackend like this:
     46
     47Add the middleware AFTER the AuthenticationMiddleware:
     48
     49    'django.contrib.auth.middleware.AuthenticationMiddleware',
     50    'django.contrib.auth.middleware.RemoteUserAuthMiddleware',
     51   
     52Add the RemoteUserAuthBackend as authentication backend:
     53    AUTHENTICATION_BACKENDS = (
     54        'django.contrib.auth.RemoteUserAuthBackend',
     55    )
     56
     57Set the REMOTE_USER_AUTH_AUTO_CREATE setting if you want to automatically add and authenticate
     58users that are unknown to django (but are already authenticated by Apache) :
     59   
     60    REMOTE_USER_AUTH_AUTO_CREATE = True
     61
     62You can also pass in a custom function to be executed AFTER a new user was added to the django database:
     63
     64    REMOTE_USER_AUTH_AFTER_CREATE = 'path.to.module.function'
     65
     66This function will be called with one parameter: the newly created User object.
     67You could use this function to set detailed info or permissions on the users (e.g. from an LDAP source).
     68
     69
     70
     71
Back to Top