Implementing LDAP authentication with Python

Breeze and cloud 2021-08-09 12:09:09
implementing ldap authentication python


LDAP brief introduction

A directory service

understand LDAP You need to know before “ A directory service ”, Directory service is a special database , Used to save descriptive 、 Attribute based details , Support filtering function . Such as : Personnel organization management , Phonebook , Address book .

LDAP

LDAP(Light Directory Access Portocol), It is based on X.500 Standard Lightweight Directory Access Protocol ,LDAP Is open Internet standard , Support cross platform Internet agreement , Widely recognized in the industry , And most of the products on the market or in the open source community have joined the right LDAP Support for , So for this kind of system , It doesn't need to be customized separately , Just go through LDAP Do a simple configuration can do authentication interaction with the server .“ Simple and crude ”, It can greatly reduce the cost of repeated development and docking .

LDAP The basic model of

Every system 、 Protocols all have their own models ,LDAP No exception , In understanding LDAP We need to know a few basic models of LDAP The tree concept of

Directory tree

  1. Directory tree : In a directory service system , The whole directory information set can be represented as a directory information tree , Each node in the tree is an entry .
  2. entry : Every entry is a record , Each item has its own unique and distinguishable name (DN).
  3. Object class : A set of properties corresponding to an entity type , Object classes are inheritable , In this way, the necessary properties of the parent class will also be inherited .
  4. attribute : Information describing an aspect of an item , A property consists of a property type and one or more property values , Attributes have required attributes and non required attributes .

keyword

keyword

English full name

meaning

dc

Domain Component

Part of the domain name , Its format is to divide the whole domain into several parts , If the domain name is example.com become dc=example,dc=com( The location of a record )

uid

User Id

user ID songtao.xu( A record of ID)

ou

Organization Unit

Organizational unit , Organizational units can contain a variety of other objects ( Including other organizational units ), Such as “oa Group ”( The organization of a record )

cn

Common Name

Public name , Such as “Thomas Johansson”( The name of a record )

sn

Surname

surname , Such as “ xu ”

dn

Distinguished Name

“uid=songtao.xu,ou=oa Group ,dc=example,dc=com”, The location of a record ( only )

rdn

Relative dn

Relative distinguished name , Similar to the relative path in the file system , It's part of the tree structure that doesn't matter , Such as “uid=tom” or “cn= Thomas Johansson”

1.Ldap The directory structure is as follows :

  • As shown in the figure above : Each entry has a unique identification name (distinguished Name ,DN) cn=doubao,ou=Ops,dc=shuyun,dc=com.DN Syntactically, it consists of multiple relative identification names (distinguished Name ,DN) Composed of , They are separated by commas .

2. stay ldap The viewing results in the system are as follows :

As shown in the figure above :ldap The basic search entry is 'dc=***,dc=com', That is, the entry you need to write when logging in as an administrator .

ldap3

ldap3 brief introduction

ldap3 It's one that can support ldap Connected Libraries , Official documents :https://ldap3.readthedocs.io/

ldap3 install

pip install ldap3

ldap3 Use

from ldap3 import Server, Connection,SUBTREE
ldap_host = 'xx.xx.x.x' #ldap Server address
ldap_port = 389 # Default 389
ldap_admin_user = 'xx' #ldap Administrator account user name
ldap_admin_password = 'xxx' #ldap Administrator account password
ldap_base_search = 'dc=xx,dc=xx' # Query domain
def ldap_auth(username, password):
'''
ldap Verification method
:param username: user name
:param password: password
:return:
'''
s = Server(host=ldap_host, port=ldap_port, use_ssl=False, get_info='ALL')
# Connect ldap The server
ldapz_admin_connection = Connection(s, user=ldap_admin_user, password=ldap_admin_password, auto_bind='NONE',
version=3,
authentication='SIMPLE', client_strategy='SYNC', auto_referrals=True,
check_names=True,
read_only=False, lazy=False,
raise_exceptions=False)
# After connecting, we have to bind To be worthy of
ldapz_admin_connection.bind()
# This is to query the entry search address of the user name you entered
res = ldapz_admin_connection.search(search_base=ldap_base_search,
search_filter='(sAMAccountName={})'.format(username),
search_scope=SUBTREE,
attributes=['cn', 'givenName', 'mail', 'sAMAccountName'],
)
try:
if res:
entry = ldapz_admin_connection.response[0]
logger.info(entry)
dn = entry['dn']
attr_dict = entry['attributes']
logger.info('attr_dic:%s' %attr_dict)
try:
# This connect Is through your user name and password, as well as the above search entry search to query
conn2 = Connection(s, user=dn, password=password, check_names=True, lazy=False, raise_exceptions=False)
conn2.bind()
# logger.info(conn2.result["description"])
# correct -success Incorrect -invalidCredentials
if conn2.result["description"] == "success":
logger.info("ldap auth pass!")
return True
else:
logger.info("username or password error!")
return False
except Exception as e:
logger.info("username or password error!")
logger.info(e)
return False
except KeyError as e:
logger.info("username or password error!")
logger.info(e)
return False
ldap_auth(xxx,xxxx)

This article is from WeChat official account. - QA A corner (sutune2020)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-10-09

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Breeze and cloud]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/08/20210809120458673z.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database