LDAP
Lightweight Directory Access Protocol
A protocol for accessing directory services, widely used for centralized user management in enterprise environments, including user authentication, organizational structure management, and authorization.
Lightweight Directory Access Protocol
A protocol for accessing directory services, widely used for centralized user management in enterprise environments, including user authentication, organizational structure management, and authorization.
LDAP (Lightweight Directory Access Protocol) is a TCP/IP-based directory service access protocol. A simplified version of the X.500 standard, it is optimized for read operations and is widely used for user authentication, organizational information lookup, and storing application settings. The default ports are 389 (LDAP) and 636 (LDAPS - SSL/TLS).
LDAP directories store data in a tree structure (DIT, Directory Information Tree). From the top down, they are composed of elements such as DC (Domain Component), OU (Organizational Unit), and CN (Common Name). For example, cn=ํ๊ธธ๋,ou=engineering,dc=example,dc=com represents the user ํ๊ธธ๋ belonging to the engineering department of the example.com domain.
Representative LDAP servers include Microsoft Active Directory (the de facto standard in Windows environments), OpenLDAP (open source), 389 Directory Server (Red Hat), and ApacheDS. In modern environments, cloud services such as AWS Directory Service and Azure AD also provide LDAP compatibility.
The typical LDAP authentication flow is: 1) the user enters a username/password, 2) the application sends a Bind request to the LDAP server, 3) the LDAP server responds with authentication success/failure, 4) if necessary, user attributes (groups, permissions, etc.) are looked up. In an SSO (Single Sign-On) environment, it may also be used together with Kerberos or SAML.
from ldap3 import Server, Connection, ALL, SUBTREE
from ldap3.core.exceptions import LDAPBindError, LDAPException
from typing import Optional, List, Dict
# LDAP ์๋ฒ ์ค์
LDAP_SERVER = "ldap://ldap.example.com:389"
LDAP_BASE_DN = "dc=example,dc=com"
LDAP_BIND_DN = "cn=admin,dc=example,dc=com"
LDAP_BIND_PASSWORD = "admin_password"
class LDAPClient:
"""LDAP ์ฐ๋ ํด๋ผ์ด์ธํธ"""
def __init__(self, server_url: str, base_dn: str):
self.server = Server(server_url, get_info=ALL)
self.base_dn = base_dn
self.conn = None
def bind_admin(self, bind_dn: str, password: str) -> bool:
"""๊ด๋ฆฌ์ ๊ณ์ ์ผ๋ก ๋ฐ์ธ๋ฉ"""
try:
self.conn = Connection(
self.server,
user=bind_dn,
password=password,
auto_bind=True
)
return True
except LDAPBindError:
return False
def authenticate_user(self, username: str, password: str) -> Optional[dict]:
"""์ฌ์ฉ์ ์ธ์ฆ (Bind ๋ฐฉ์)"""
# 1. ๋จผ์ ์ฌ์ฉ์ DN ๊ฒ์
user_dn = self._find_user_dn(username)
if not user_dn:
return None
# 2. ์ฌ์ฉ์ ๊ณ์ ์ผ๋ก ์ง์ ๋ฐ์ธ๋ฉ ์๋
try:
user_conn = Connection(
self.server,
user=user_dn,
password=password,
auto_bind=True
)
user_conn.unbind()
# 3. ์ธ์ฆ ์ฑ๊ณต ์ ์ฌ์ฉ์ ์ ๋ณด ๋ฐํ
return self.get_user_info(username)
except LDAPBindError:
return None # ์ธ์ฆ ์คํจ
def _find_user_dn(self, username: str) -> Optional[str]:
"""์ฌ์ฉ์ DN ๊ฒ์"""
search_filter = f"(sAMAccountName={username})" # AD ํ๊ฒฝ
# OpenLDAP์ธ ๊ฒฝ์ฐ: f"(uid={username})"
self.conn.search(
search_base=self.base_dn,
search_filter=search_filter,
search_scope=SUBTREE,
attributes=['distinguishedName']
)
if self.conn.entries:
return str(self.conn.entries[0].distinguishedName)
return None
def get_user_info(self, username: str) -> Optional[dict]:
"""์ฌ์ฉ์ ์์ธ ์ ๋ณด ์กฐํ"""
search_filter = f"(sAMAccountName={username})"
self.conn.search(
search_base=self.base_dn,
search_filter=search_filter,
search_scope=SUBTREE,
attributes=[
'cn', 'mail', 'displayName', 'department',
'memberOf', 'telephoneNumber', 'title'
]
)
if not self.conn.entries:
return None
entry = self.conn.entries[0]
return {
'username': username,
'dn': str(entry.entry_dn),
'name': str(entry.cn) if entry.cn else None,
'email': str(entry.mail) if entry.mail else None,
'display_name': str(entry.displayName) if entry.displayName else None,
'department': str(entry.department) if entry.department else None,
'title': str(entry.title) if entry.title else None,
'groups': [str(g) for g in entry.memberOf] if entry.memberOf else []
}
def get_user_groups(self, username: str) -> List[str]:
"""์ฌ์ฉ์๊ฐ ์ํ ๊ทธ๋ฃน ๋ชฉ๋ก ์กฐํ"""
user_info = self.get_user_info(username)
if not user_info:
return []
# memberOf์์ ๊ทธ๋ฃน CN๋ง ์ถ์ถ
groups = []
for group_dn in user_info.get('groups', []):
# "CN=Developers,OU=Groups,DC=example,DC=com" -> "Developers"
cn_part = group_dn.split(',')[0]
if cn_part.startswith('CN='):
groups.append(cn_part[3:])
return groups
def is_member_of(self, username: str, group_name: str) -> bool:
"""ํน์ ๊ทธ๋ฃน ๋ฉค๋ฒ์ญ ํ์ธ"""
groups = self.get_user_groups(username)
return group_name in groups
def search_users(self, search_term: str, limit: int = 100) -> List[dict]:
"""์ฌ์ฉ์ ๊ฒ์"""
search_filter = f"(&(objectClass=person)(|(cn=*{search_term}*)(mail=*{search_term}*)))"
self.conn.search(
search_base=self.base_dn,
search_filter=search_filter,
search_scope=SUBTREE,
attributes=['cn', 'mail', 'sAMAccountName'],
size_limit=limit
)
results = []
for entry in self.conn.entries:
results.append({
'username': str(entry.sAMAccountName) if entry.sAMAccountName else None,
'name': str(entry.cn) if entry.cn else None,
'email': str(entry.mail) if entry.mail else None,
})
return results
def close(self):
"""์ฐ๊ฒฐ ์ข
๋ฃ"""
if self.conn:
self.conn.unbind()
# ์ฌ์ฉ ์์
if __name__ == "__main__":
# LDAP ํด๋ผ์ด์ธํธ ์ด๊ธฐํ
ldap = LDAPClient(LDAP_SERVER, LDAP_BASE_DN)
# ๊ด๋ฆฌ์๋ก ๋ฐ์ธ๋ฉ
if ldap.bind_admin(LDAP_BIND_DN, LDAP_BIND_PASSWORD):
print("๊ด๋ฆฌ์ ๋ฐ์ธ๋ฉ ์ฑ๊ณต")
# ์ฌ์ฉ์ ์ธ์ฆ ํ
์คํธ
user = ldap.authenticate_user("hong.gildong", "user_password")
if user:
print(f"์ธ์ฆ ์ฑ๊ณต: {user['display_name']} ({user['email']})")
print(f"์์ ๊ทธ๋ฃน: {ldap.get_user_groups('hong.gildong')}")
# ๊ถํ ํ์ธ
if ldap.is_member_of("hong.gildong", "Administrators"):
print("๊ด๋ฆฌ์ ๊ถํ ์์")
else:
print("์ธ์ฆ ์คํจ")
# ์ฌ์ฉ์ ๊ฒ์
users = ldap.search_users("๊ฐ๋ฐ")
for u in users:
print(f"๊ฒ์ ๊ฒฐ๊ณผ: {u['name']} - {u['email']}")
ldap.close()
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free