Django Python - Ldap Authentication

2019-07-20 04:06发布

问题:

I am currently work on Django Python . My aim to authenticate the user from the Ldap directory . I do have my python code to access the ldap directory and retrieve the information.

Code :

import ldap
try:
        l = ldap.open("ldap.forumsys.com")
        l.protocol_version = ldap.VERSION2
        username = "cn=read-only-admin,dc=example,dc=com"
        password = "password"
        l.simple_bind(username,password)

except ldap.LDAPError,e:
        print e

My doubt is that , how would i implement this in my django? . How do use these code in django and to implement it?

Thanks in advance

回答1:

It is almost the same, you have to code your specific search about ldap (sam accountName usually) when you want it, normally after submit call coming from a user´s login.

userDN = ""
passwordUser = ""
base_dn = 'node where we start to seach, from your AD structure'
#attrs = ['description', 'telephoneNumber', 'title', 'mail' , 'lastLogon', 'memberOf', 'accountExpires',]
attrs = []

def myAccount(request):
    con = ldap.initialize("ldap://ldapserver")
    con.simple_bind_s( userDN, passwordUser )
    filter = '(sAMAccountName=' + "loginName" + ')'
    user = con.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs )
    con.unbind()

    userInfoList = []
    for key, value in user[0][1].items():
        userInfoList +=  [userInfo(key, value)]

    return render_to_response('template.html',{'userInfoList':userInfoList, 'dnUser': user[0][0]}, context_instance = RequestContext(request))

In code below, an specific template is calling to myAccount method, in this method we use ldap complement for doing a search over LDAP, by an user authorized in DN for doing searches. After that we recover the info obtained by this search.

Hope it helps. Any doubt you could have, just let me know :)