Login

Active Directory Authentication With Groups

Author:
dreilly1982
Posted:
March 6, 2013
Language:
Python
Version:
1.3
Tags:
Django Python Active-Directory Authentication Groups
Score:
2 (after 2 ratings)

This is a authentication backend for Django, to authenticate via Active Directory. This pulls all group information out of Active Directory and allows for multiple group memberships.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# settings.py
# active directory authentication module
AD_DNS_NAME = 'your.domain.com'	 # FQDN of your DC (using just the Domain Name to utilize all DC's)
# If using non-SSL use these
#AD_LDAP_PORT=389
#AD_LDAP_URL='ldap://%s:%s' % (AD_DNS_NAME,AD_LDAP_PORT)
# If using SSL use these:
AD_LDAP_PORT=636
AD_LDAP_URL='ldaps://%s:%s' % (AD_DNS_NAME,AD_LDAP_PORT)
AD_SEARCH_DN = 'dc=your,dc=domain,dc=com'
AD_NT4_DOMAIN = 'YOURDOMAIN'
AD_SEARCH_FIELDS = ['mail','givenName','sn','sAMAccountName','memberOf']
AD_MEMBERSHIP_ADMIN = ['AdminGroup']	# this ad group gets superuser status in django
# only members of this group can access
AD_MEMBERSHIP_REQ = AD_MEMBERSHIP_ADMIN + ['Group1',
                                           'Group2',
                                           'Group3']
AD_CERT_FILE = '/path/to/ca/cert'	# this is the certificate of the Certificate Authority issuing your DCs certificate
AD_DEBUG=True #Set to false for prod, Slows things down ALOT
AD_DEBUG_FILE='/tmp/ldap.debug'


AUTHENTICATION_BACKENDS = (
    '<your project name here>.backend.ActiveDirectoryAuthenticationBackend'
    #'django.contrib.auth.backends.ModelBackend' #Comment out to prevent authentication from DB
)


# backend.py
import ldap
import os
import re
import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.auth.backends import ModelBackend #Need to include this as it has been disabled

#Need to have this class inherit from ModelBackend to have permissions inherit to groups.
class ActiveDirectoryAuthenticationBackend(ModelBackend):

    """
    This authentication backend authenticates against Active directory.
    It updates the user objects according to the settings in the AD and is
    able to map specific groups to give users admin rights.
    """

    def __init__(self):
        """ initialise a debuging if enabled """
        self.debug = settings.AD_DEBUG
        if len(settings.AD_DEBUG_FILE) > 0 and self.debug:
            self.debugFile = settings.AD_DEBUG_FILE
            # is the debug file accessible?
            if not os.path.exists(self.debugFile):
                open(self.debugFile,'w').close()
            elif not os.access(self.debugFile, os.W_OK):
                raise IOError("Debug File is not writable")
        else:
            self.debugFile = None

    def authenticate(self,username=None,password=None):
        try:
            if len(password) == 0:
                return None
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,settings.AD_CERT_FILE)
            l = ldap.initialize(settings.AD_LDAP_URL)
            l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
            binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN)
            l.simple_bind_s(binddn,password)
            l.unbind_s()
            return self.get_or_create_user(username,password)

        except ImportError:
            self.debug_write('import error in authenticate')
        except ldap.INVALID_CREDENTIALS:
            self.debug_write('%s: Invalid Credentials' % username)

    def get_or_create_user(self, username, password):
        """ create or update the User object """
        # get user info from AD
        userInfo = self.get_user_info(username, password)

        # is there already a user?
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            if userInfo is not None:
                user = User(username=username, password=password)
                self.debug_write('create new user %s' % username)
                user.save() #Creates initial user so groups can be manipulated
            else:
                return None

        ## update the user objects
        # group mapping for the access rights
        user.groups.clear() #Clears user groups in case of changes
        for group in userInfo['idGroup']:  #Adds all groups user is member of
            g=Group.objects.get(name=group)
            user.groups.add(g)
        if userInfo['isAdmin']:
            user.is_staff = True
            user.is_superuser = True
        elif userInfo:
            user.is_staff = True
            user.is_superuser = False
        else:
            user.is_active = False

        # personal data
        user.first_name = userInfo['first_name']
        user.last_name = userInfo['last_name']
        user.email = userInfo['mail']

        # cache the AD password
        user.set_password('ldap authenticated') #puts in a dummy PW doesn't matter but use this to put a hash in

        user.save()

        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def debug_write(self,message):
        """ handle debug messages """
        if self.debugFile is not None:
            fObj = open(self.debugFile, 'a')
            now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
            fObj.write("%s\t%s\n" % (now,message))
            fObj.close()

    def check_group(self,membership):
        """ evaluate ADS group memberships """
        self.debug_write("Evaluating group membership")
        isValid = False
        isAdmin = False
        idGroup = []
        pattern = re.compile(r'^CN=ID (?P<groupName>[\w|\d|\s]+),')  #Our AD groups were mirrored with the Django groups but prefaced with "ID " (notice the space)
        for group in membership:
            groupMatch = pattern.match(group)
            if groupMatch:
                thisGroup = groupMatch.group('groupName')
                idGroup.append(thisGroup)
                if thisGroup in settings.AD_MEMBERSHIP_REQ:
                    isValid = True
                if thisGroup in settings.AD_MEMBERSHIP_ADMIN:
                    isAdmin = True

        if isAdmin:
            self.debug_write('is admin user')
        elif isValid:
            self.debug_write('is normal user')
        else:
            self.debug_write('does not have the AD group membership needed')

        return isAdmin, isValid, idGroup

    def get_user_info(self, username, password):
        """ get user info from ADS to a dictionary """
        try:
            userInfo = {
            'username' : username,
            'password' : password,
            }
            # prepare LDAP connection
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,settings.AD_CERT_FILE)
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,ldap.OPT_X_TLS_NEVER) #This required to avoid CN mismatches
            ldap.set_option(ldap.OPT_REFERRALS,0) # DO NOT TURN THIS OFF OR SEARCH WON'T WORK!

            # initialize
            self.debug_write('ldap.initialize...')
            l = ldap.initialize(settings.AD_LDAP_URL)
            l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)

            # bind
            binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN)
            self.debug_write('ldap.bind %s' % binddn)
            l.bind_s(binddn,password)

            # search
            self.debug_write('search...')
            result = l.search_ext_s(settings.AD_SEARCH_DN,ldap.SCOPE_SUBTREE,"sAMAccountName=%s" % username,settings.AD_SEARCH_FIELDS)[0][1]
            self.debug_write("results in %s" % result)

            # Validate that they are a member of review board group
            if result.has_key('memberOf'):
                membership = result['memberOf']
            else:
                self.debug_write('AD user has no group memberships')
                return None

            # user ADS Groups
            isAdmin, isValid, idGroup = self.check_group(membership)

            if not isValid:
                return None

            userInfo['isAdmin'] = isAdmin
            userInfo['idGroup'] = idGroup
            self.debug_write(idGroup)

            # get user info from ADS
            # get email
            if result.has_key('mail'):
                mail = result['mail'][0]
            else:
                mail = ""

            userInfo['mail'] = mail
            self.debug_write("mail=%s" % mail)

            # get surname
            if result.has_key('sn'):
                last_name = result['sn'][0]
            else:
                last_name = None

            userInfo['last_name'] = last_name
            self.debug_write("last_name=%s" % last_name)

            # get display name
            if result.has_key('givenName'):
                first_name = result['givenName'][0]
            else:
                first_name = None

            userInfo['first_name'] = first_name
            self.debug_write("first_name=%s" % first_name)

            # LDAP unbind
            l.unbind_s()
            return userInfo

        except Exception, e:
            self.debug_write("exception caught!")
            self.debug_write(e)
            return None

More like this

Comments

miquelcamprodon (on September 24, 2013):

Thank you for the snippet. I had to perform a minor change to get it working. In the snippet it is assumed that all groups are already created. In my case I had to create the ones that did not yet exist. I also added only the groups listed in the variable.

Here is my modification:

... line 97 ...
for group in userInfo['idGroup]:
    if group in settings.AD_MEMBERSHIP_REQ:
        try:        
            g=Group.objects.get(name=group)
        except:
            g=Group()
            g.name = group
            g.save()

        user.groups.add(g)
... line 100 ...

#

miquelcamprodon (on September 24, 2013):

... line 97 ...

for group in userInfo['idGroup']: #Adds all groups user is member of if group in settings.AD_MEMBERSHIP_REQ: try: g=Group.objects.get(name=group) except: g=Group() g.name=group g.save() user.groups.add(g)

... line 101 ...

#

Please login first before commenting.