title: Authenticating against active directory using python + ldap
body: <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
  
  <p>I can't even bind to perform a simple query:</p>
  
  <pre><code>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 = "(&amp;(objectClass=user)(sAMAccountName="+un+"))"
  Attrs = ["displayName"]
  
  l = ldap.initialize(Server)
  l.protocol_version = 3
  print l.simple_bind_s(DN, Secret)
  
  r = l.search(Base, 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
  
  sys.exit()
  </code></pre>
  
  <p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
  
  <p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
  
  <blockquote>
    <p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
  </blockquote>
  
  <p>Or </p>
  
  <blockquote>
    <p>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'}</p>
  </blockquote>
  
  <p>What am I missing out to bind properly?</p>
  
  <p>I am getting the same errors on fedora and windows.</p>