Ticket #689: remote_user_2.diff

File remote_user_2.diff, 6.7 KB (added by Koen Biermans <koen.biermans@…>, 10 years ago)

Modified version without settings

  • 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                user = self.unknown_user(username)
     35        return user
     36
     37    def unknown_user(username):
     38        # Auto-create user
     39        password = User.objects.make_random_password()
     40        user = User.objects.create_user(username, '', password)
     41        user.is_staff = False
     42        user.save()
     43        user = self.configure_user(user)
     44        return user
     45
     46    def configure_user(user):
     47        # Override this to set custom properties for a new user
     48        return user
     49
  • 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
  • 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
     57Subclassing the RemoteUserAuthBackend
     58==============================
     59
     60By default, the RemoteUserAuthBackend will simply add any non existing user to the Django user database.
     61Since the user was let in by Apache, it is supposed to be a valid user.
     62However, you may override this behaviour by subclassing the RemoteUserAuthBackend:
     63
     64Override the auto-creation of users
     65----------------------------------
     66The RemoteUserAuthBackend has a function unknown_user(username), which by default creates a new
     67User object for any user not yet known to Django. It returns the new user object.
     68If you don't want to auto-create new users, you may override this function to return None.
     69
     70Example:
     71
     72    in settings.py:
     73   
     74        AUTHENTICATION_BACKENDS = (
     75            'myproject.utils.MyOwnRemoteUserAuthBackend',
     76        )
     77   
     78    in myproject.utils:
     79   
     80        from django.contrib.auth.backends import RemoteUserAuthBackend
     81   
     82        class MyOwnRemoteUserAuthBackend(RemoteUserAuthBackend):
     83            def unknown_user(self, username):
     84                return None
     85
     86
     87Configure the properties for the newly created user
     88-------------------------------------------------
     89The RemoteUserAuthBackend has a function configure_user(user), which by default does nothing to
     90the new user object.
     91
     92You could however use this function to set detailed info or permissions on the users (e.g. using info
     93from an LDAP source).
     94
     95Example:
     96
     97    in settings.py:
     98   
     99        AUTHENTICATION_BACKENDS = (
     100            'myproject.utils.MyOwnRemoteUserAuthBackend',
     101        )
     102   
     103    in myproject.utils:
     104   
     105        from django.contrib.auth.backends import RemoteUserAuthBackend
     106   
     107        class MyOwnRemoteUserAuthBackend(RemoteUserAuthBackend):
     108            def configure_user(self, user):
     109                # put your custom code here
     110                user.last_name = user.username
     111                user.save()
     112                #
     113                return user
Back to Top