django-auth-ldap / django-auth-ldap

Django authentication backend that authenticates against an LDAP service.
https://django-auth-ldap.readthedocs.io/
BSD 2-Clause "Simplified" License
334 stars 96 forks source link

user.ldap_user not available? #179

Open trnc-ck opened 4 years ago

trnc-ck commented 4 years ago

Hey,

I'm able to login. The user data gets populated in the django user model. I'm using JWT authentication through django rest framework. The only thing which doesn't work is user.ldap_user. It just raises

'User' object has no attribute 'ldap_user'

when e.g. print the user

print(request.user.ldap_user.__dict__)

Here's my config:

AUTH_LDAP_SERVER_URI = "ldap://ldap_container:389"

AUTH_LDAP_BIND_DN = "cn=admin,dc=foo,dc=bar"
AUTH_LDAP_BIND_PASSWORD = "secret"
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    "ou=users,dc=foo,dc=bar", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
)

AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
    "ou=groups,dc=foo,dc=bar",
    ldap.SCOPE_SUBTREE,
    "(objectClass=groupOfNames)",
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")

AUTH_LDAP_REQUIRE_GROUP = "cn=users,ou=groups,dc=foo,dc=bar"

AUTH_LDAP_USER_ATTR_MAP = {
    "username": "uid",
    "first_name": "cn",
    "last_name": "sn",
    "email": "mail",
}

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_active": "cn=users,ou=groups,dc=foo,dc=bar",
    "is_staff": "cn=users,ou=groups,dc=foo,dc=bar",
    "is_superuser": "cn=users,ou=groups,dc=foo,dc=bar",
}

AUTH_LDAP_ALWAYS_UPDATE_USER = True

AUTH_LDAP_FIND_GROUP_PERMS = True

AUTH_LDAP_CACHE_TIMEOUT = 3600

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "django_auth_ldap.backend.LDAPBackend",
)

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "loggers": {"django_auth_ldap": {"level": "DEBUG", "handlers": ["console"]}},
}
serk12 commented 4 years ago

I'm having similar problems, basically if the user is new there is no problem, but if it already exists in the BD ´ldap_user` won't work

Edit: I'm using a custom backend following the wiki tutorial Edit2: still not the best solution but you can "fix it" by:

from django_auth_ldap.backend import LDAPBackend, _LDAPUser
### all your code, and when you need your ldap_user add:###
if not hasattr(user_ldap, 'ldap_user'):
    user_ldap.ldap_user = _LDAPUser(self, username)