首页 > 其他 > 详细

Django+ldap认证示例

时间:2021-01-07 19:01:32      阅读:32      评论:0      收藏:0      [点我收藏+]

settings.py 配置以下变量,参与AD认证

AUTH_LDAP_SERVER_URI = ldap://10.108.198.6:389
AUTH_LDAP_BIND_DN = CN=test,OU=Service Accounts,DC=lenovo,dc=com
AUTH_LDAP_BIND_PASSWORD = password

AUTH_LDAP_USER_SEARCH = LDAPSearch(
    base_dn=OU=User Accounts,DC=lenovo,DC=com,
    scope=ldap.SCOPE_SUBTREE,
    filterstr=(sAMAccountName=%(user)s)
)

AUTH_LDAP_USER_ATTR_MAP = {
    first_name: givenName,
    last_name: sn,
    username: sAMAccountName,
    email: mail,
}

 

如果需要在ad认证完成后进行其它操作,可自定义认证模型,netops是应用名,在settings.py同级目录下创建backends.py,并在在settings.py中增加

AUTHENTICATION_BACKENDS = (
    netops.backends.AuthLDAPBackendBackend,
    netops.backends.AuthModelBackend,
)

backends.py 代码如下

import re
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import Group
import logging


class AuthLDAPBackendBackend(LDAPBackend):
    def authenticate_ldap_user(self, ldap_user, password):
        """
        Returns an authenticated Django user or None.
        """
        user = ldap_user.authenticate(password)
        if user:
            if not user.is_active or not user.is_staff:
                user.is_active = True
                user.is_staff = True
                user.save()
            try:
                pass
                # your code...
            except Exception as e:
                logging.error(e)
        return user

    def authenticate(self, request, username=None, password=None, **kwargs):
        if password or self.settings.PERMIT_EMPTY_PASSWORD:
            ldap_user = _LDAPUser(self, username=username.strip(), request=request)
            user = self.authenticate_ldap_user(ldap_user, password)
        else:
            logging.debug(Rejecting empty password for {}.format(username))
            user = None
        if user:
            # your code...
            pass
        return user


class AuthModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = super(AuthModelBackend, self).authenticate(request, username, password, **kwargs)
        return user

 

Django+ldap认证示例

原文:https://www.cnblogs.com/luoyj2/p/14247802.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!