Authenticating against active directory using python + ldap

How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.

I can't even bind to perform a simple query:

import sys
import ldap

Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]

Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]

l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)

r =, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
  displayName = Attrs['displayName'][0]
  print displayName


Running this with password username gives me one of two errors:

Invalid Credentials - When I mistype or intentionally use wrong credentials it fails to authenticate.

ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}


ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}

What am I missing out to bind properly?

I am getting the same errors on fedora and windows.

Asked by: Aldus943 | Posted: 28-01-2022

Answer 1

I was missing

l.set_option(ldap.OPT_REFERRALS, 0)

From the init.

Answered by: Edgar276 | Posted: 01-03-2022

Answer 2

If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server:

import win32security
token = win32security.LogonUser(
authenticated = bool(token)

Answered by: Lily283 | Posted: 01-03-2022

Answer 3

That worked for me, l.set_option(ldap.OPT_REFERRALS, 0) was the key to access the ActiveDirectory. Moreover, I think that you should add an "con.unbind()" in order to close the connection before finishing the script.

Answered by: William339 | Posted: 01-03-2022

Answer 4

Here's some simple code that works for me.

import ldap  # run 'pip install python-ldap' to install ldap module.
conn ="")
conn.simple_bind_s("", "mypassword")

This is based on a previous answer.

Answered by: Darcy150 | Posted: 01-03-2022

Answer 5

if you have Kerberos installed and talking to AD, as would be the case with, say, Centrify Express installed and running, you might just use python-kerberos. E.g.

import kerberos

would return True a user 'joe' has password 'pizza' in the Kerberos realm X.PIZZA.COM. (typically, I think, the latter would be the same as the name of the AD Domain)

Answered by: Anna410 | Posted: 01-03-2022

Answer 6

Based on the excellent ldap3 tutorial:

from ldap3 import Server, Connection, ALL, NTLM
server = Server('server_name_or_ip', get_info=ALL)
conn = Connection(server, user="user_name", password="password", auto_bind=True)

I did the above in Python3 but it's supposed to be compatible with Python 2.

Answered by: Aldus588 | Posted: 01-03-2022

Answer 7

I see your comment to @Johan Buret about the DN not fixing your problem, but I also believe that is what you should look into.

Given your example, the DN for the default administrator account in AD will be: cn=Administrator,cn=Users,dc=mydomain,dc=co,dc=uk - please try that.

Answered by: Sydney294 | Posted: 01-03-2022

Answer 8

I tried to add

l.set_option(ldap.OPT_REFERRALS, 0)

but instead of an error Python just hangs and won't respond to anything any more. Maybe I'm building the search query wrong, what is the Base part of the search? I'm using the same as the DN for the simple bind (oh, and I had to do l.simple_bind, instead of l.simple_bind_s):

import ldap
local = ldap.initialize("ldap://")
#my pc is not actually connected to this domain 
result_id ="CN=staff,DC=mydomain,DC=com", ldap.SCOPE_SUBTREE, "cn=foobar", None)
local.set_option(ldap.OPT_REFERRALS, 0)
result_type, result_data = local.result(result_id, 0)

I'm using AD LDS and the instance is registered for the current account.

Answered by: Melissa551 | Posted: 01-03-2022

Answer 9

I had the same issue, but it was regarding the password encoding


Solved the problem.

Answered by: Aston105 | Posted: 01-03-2022

Answer 10

Use a Distinguished Name to log on your system."CN=Your user,CN=Users,DC=b2t,DC=local" It should work on any LDAP system, including AD

Answered by: Rafael730 | Posted: 01-03-2022

Answer 11

For me changing from simple_bind_s() to bind() did the trick.

Answered by: Tess933 | Posted: 01-03-2022

Similar questions

authentication - Authenticating with Coinbase's Exchange's API (HMAC) using requests in Python

I am implementing Coinbase's exchange API using custom auth in requests-python. The following code works with all the (authenticated) GET-based calls, but fails for all the authenticated POST-based calls (I haven't tried with DELETE or UPDATE verbs). I don't understand why the signature wouldn't work for both, because the payload is timestamp + method + p...

authentication - Authenticating Users with Python OAuth 2

Authenticate Users I am using google bookshelf tutorial. I have done exactly what written there. But I am not able to run the application on my local server. I tried adding GOOGLE_APPLICATION_CREDENTIALS in but no help. Can someone please help me to understand this p...

python - Django Authentication Form not authenticating and redirecting

After I put the correct password, it should redirect to "/articles" , BUT IT'S REFRESHING THE LOGIN PAGE ONLY. def login(request): if request.method == 'POST': form = a_form(data=request.POST) if form.is_valid(): return redirect('/articles') else: form = a_form() context = {'form': form} return render(request, 'accounts/login.html', c...

Python Authentication API

I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing. I have found several method in web framework such as django or turbogears. I just want a kind of username-password association stored into a local file. I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).

Can I implement a web user authentication system in python without POST?

My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible? If it's not, how would you do it with POST? Just out of curiosity. Cheers!

javascript - Django authentication and Ajax - URLs that require login

I want to add some Ajax-niceness to my Django-coded website. In my Django code, I use the @login_required decorator from django.contrib.auth.decorators to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass...

python - User Authentication in Django

is there any way of making sure that, one user is logged in only once? I would like to avoid two different persons logging into the system with the same login/password. I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality. Cheers, Thanks for the responses!

authentication - In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?

I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or 2.6 (unfamiliar) to do this. I think I need to have some way to authenticate against the pr...

Python - downloading a file over HTTP with progress bar and basic authentication

I'm using urllib.urlretrieve to download a file, and implementing a download progress bar using the reporthook parameter. Since urlretrieve doesn't directly support authentication, I came up with import urllib def urlretrieve_with_basic_auth(url, filename=None, reporthook=None, data=None, username="", password=""): class OpenerWith...

authentication - What's the best way to specify a proxy with username and password for an **https** connection in python?

I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it . Please help me. Thanks.

python - Using AD as authentication for Django

I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities. Does anyone have a good example of this?

python - Google Data API authentication

I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs ...

json - Authentication Required - Problems Establishing AIM OSCAR Session using Python

I'm writing a simple python script that will interface with the AIM servers using the OSCAR protocol. It includes a somewhat complex handshake protocol. You essentially have to send a GET request to a specific URL, receive XML or JSON encoded reply, extract a special session token and secret key, then generate a response using the token and the key. ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python