Linightz
Linightz

Reputation: 185

django-auth-ldap failed to map the username to a DN after switching to LDAPS

I'm building a django project for my company, I had settings like below when I just use simple bind without SSL:

AUTH_LDAP_SERVER_URI = 'ldap://some.example.server:389'
AUTH_LDAP_BASE_DN = 'some-base-dn'
AUTH_LDAP_BIND_DN = 'some-bind-dn'
AUTH_LDAP_BIND_PASSWORD = 'some-password'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)')

and it worked perfectly.

However, due to the security enhancement of our company's LDAP server, we're asked to use LDAP over SSL. So I get a certificate and change my code like this:

AUTH_LDAP_GLOBAL_OPTIONS = {
    ldap.OPT_X_TLS_REQUIRE_CERT: True,
    ldap.OPT_X_TLS_DEMAND: True,
    ldap.OPT_REFERRALS: 0,
    ldap.OPT_X_TLS_CACERTFILE: '/etc/ssl/certs/mycertfile.pem'
}
AUTH_LDAP_SERVER_URI = 'ldaps://some.example.server:636'
AUTH_LDAP_BASE_DN = 'some-base-dn'
AUTH_LDAP_BIND_DN = 'some-bind-dn'
AUTH_LDAP_BIND_PASSWORD = 'some-password'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)')

It no longer works. It keeps saying search_s(xxx) returned 0 objects: Authentication failed for : failed to map the username to a DN.

But if I change the filter string for the LDAPSearch() from

'(sAMAccountName=%(user)s)'

to

'(sAMAccountName=<hard-coded-id>)'

it works.

I've been trying to dig out why this happens and so far no luck. Does anyone have any idea why this is happening?

Much Appreciated.

Upvotes: 2

Views: 5750

Answers (1)

Linightz
Linightz

Reputation: 185

My apology, it was a user error. The code below works perfectly.

AUTH_LDAP_GLOBAL_OPTIONS = {
    ldap.OPT_X_TLS_REQUIRE_CERT: True,
    ldap.OPT_X_TLS_DEMAND: True,
    ldap.OPT_REFERRALS: 0,
    ldap.OPT_X_TLS_CACERTFILE: '/etc/ssl/certs/mycertfile.pem'
}
AUTH_LDAP_SERVER_URI = 'ldaps://some.example.server:636'
AUTH_LDAP_BASE_DN = 'some-base-dn'
AUTH_LDAP_BIND_DN = 'some-bind-dn'
AUTH_LDAP_BIND_PASSWORD = 'some-password'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)')

Upvotes: 2

Related Questions