在Django中以ldapUser的身份登录电子邮件

时间:2018-03-06 10:48:36

标签: python django authentication ldap

我目前正在开发我的webapp。截至目前,我可以使用用户名(sAMAccountName)登录,但我想使用电子邮件地址登录。我查了一些后端,但没有一个可以帮助我。

这是我的setting.py

AUTH_LDAP_SERVER_URI = "ldap://192.168.4.123"
AUTH_LDAP_BIND_DN = "username"
AUTH_LDAP_BIND_PASSWORD = "password"
AUTH_LDAP_CONNECTION_OPTIONS = {
    ldap.OPT_DEBUG_LEVEL: 1,
    ldap.OPT_REFERRALS: 0
}

AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)")
AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType()

AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
    "dn": "distinguishedName",
}

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_active": "CN=users,cn=users,DC=domain,DC=com",
    "is_staff": "CN=users,cn=users,DC=domain,DC=com",
    "is_superuser": "CN=users,cn=users,DC=domain,DC=com"
}

AUTH_LDAP_ALWAYS_UPDATE_USER = True

LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson"

AUTH_LDAP_FIND_GROUP_PERMS = True

AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600

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

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'stream_to_console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django_auth_ldap': {
            'handlers': ['stream_to_console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

也许你有一个很好的后端或者我错过了一些东西。我也尝试过:

AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=sbvg,DC=ch", ldap.SCOPE_SUBTREE, "(mail=%(user)s)")

但是它会创建一个用户名为user@domain.com的用户,这也是错误的。

1 个答案:

答案 0 :(得分:0)

用户模型已经在Django中构建,使用电子邮件作为用户名,您需要在该模型中进行一些更改。 使用下面的代码来自定义您的用户名并将其粘贴到models.py。

from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    objects = UserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [] # Email & Password are required by default.

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.active

Django为用户管理器提供了内置方法。我们必须自定义它们才能使我们的自定义用户模型正常工作。下面的代码也将用models.py

编写
class UserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_staffuser(self, email, password):
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user

使用这两个命令: python manage.py makemigrations [app name] python manage.py migrate

现在打开settings.py: AUTH_USER_MODEL = 'app.User'

再次运行: python manage.py makemigrations [app name] python manage.py migrate

现在使用电子邮件创建新用户并尝试登录。它似乎太复杂了,但我希望它会起作用。

了解更多信息,请参阅此video