First commit from the robot

This commit is contained in:
2025-10-16 14:57:56 -07:00
committed by Spencer Jones
parent c747ae4ce3
commit 0bac69c801
18 changed files with 3952 additions and 0 deletions

336
examples/README.md Normal file
View File

@@ -0,0 +1,336 @@
# LDAP Docker Examples
This directory contains example scripts and applications demonstrating how to use the LDAP server for authentication and user management.
## Available Examples
### 1. Simple Authentication (`simple_auth.py`)
A Python script demonstrating basic LDAP authentication and user information retrieval.
**Features:**
- Authenticate users with username/password
- Retrieve detailed user information
- Get user group memberships
- List all users in the directory
**Usage:**
```bash
# Authenticate a user (default: jdoe)
python examples/simple_auth.py
# Authenticate with custom credentials
python examples/simple_auth.py --username jsmith --password password123
# List all users
python examples/simple_auth.py --list-users
# Use a different LDAP server
python examples/simple_auth.py --server ldaps://localhost:636
```
**Example Output:**
```
🔐 LDAP Authentication Example
Server: ldap://localhost:389
Attempting to authenticate user: jdoe
✅ Authentication successful for user: jdoe
✅ Authentication successful!
Fetching user information...
==================================================
USER INFORMATION
==================================================
Username: jdoe
Full Name: John Doe
First Name: John
Last Name: Doe
Email: jdoe@testing.local
UID Number: 10001
GID Number: 10001
DN: uid=jdoe,ou=people,dc=testing,dc=local
==================================================
Fetching user groups...
User belongs to 2 group(s):
• developers
• users
```
## Using in Your Application
### Python with ldap3
```python
from ldap3 import Server, Connection
# Connect and authenticate
server = Server('ldap://localhost:389')
conn = Connection(
server,
user='uid=jdoe,ou=people,dc=testing,dc=local',
password='password123',
auto_bind=True
)
# Search for users
conn.search(
'dc=testing,dc=local',
'(objectClass=inetOrgPerson)',
attributes=['uid', 'cn', 'mail']
)
for entry in conn.entries:
print(f"{entry.cn}: {entry.mail}")
conn.unbind()
```
### Using ldapsearch (Command Line)
```bash
# Search for a user
ldapsearch -H ldap://localhost:389 \
-D "cn=admin,dc=testing,dc=local" \
-w admin_password \
-b "dc=testing,dc=local" \
"(uid=jdoe)"
# List all users
ldapsearch -H ldap://localhost:389 \
-D "cn=admin,dc=testing,dc=local" \
-w admin_password \
-b "ou=people,dc=testing,dc=local" \
"(objectClass=inetOrgPerson)" \
uid cn mail
```
### Web Application Integration
#### Flask Example
```python
from flask import Flask, request, jsonify
from ldap3 import Server, Connection
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
server = Server('ldap://localhost:389')
user_dn = f'uid={username},ou=people,dc=testing,dc=local'
try:
conn = Connection(server, user=user_dn, password=password)
if conn.bind():
return jsonify({'status': 'success', 'message': 'Authenticated'})
else:
return jsonify({'status': 'error', 'message': 'Invalid credentials'}), 401
except:
return jsonify({'status': 'error', 'message': 'Authentication failed'}), 401
```
#### Django Example
```python
# settings.py
import ldap
from django_auth_ldap.config import LDAPSearch
AUTH_LDAP_SERVER_URI = "ldap://localhost:389"
AUTH_LDAP_BIND_DN = "cn=admin,dc=testing,dc=local"
AUTH_LDAP_BIND_PASSWORD = "admin_password"
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"ou=people,dc=testing,dc=local",
ldap.SCOPE_SUBTREE,
"(uid=%(user)s)"
)
AUTHENTICATION_BACKENDS = [
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
]
```
## Common Integration Patterns
### 1. Simple Bind Authentication
The most straightforward approach - try to bind with user credentials:
```python
def authenticate_user(username, password):
server = Server('ldap://localhost:389')
user_dn = f'uid={username},ou=people,dc=testing,dc=local'
conn = Connection(server, user=user_dn, password=password)
return conn.bind()
```
### 2. Search and Bind
Search for the user first, then authenticate:
```python
def authenticate_user(username, password):
# First, search for the user with admin credentials
server = Server('ldap://localhost:389')
admin_conn = Connection(
server,
user='cn=admin,dc=testing,dc=local',
password='admin_password',
auto_bind=True
)
admin_conn.search(
'ou=people,dc=testing,dc=local',
f'(uid={username})',
attributes=['dn']
)
if not admin_conn.entries:
return False
user_dn = admin_conn.entries[0].entry_dn
admin_conn.unbind()
# Now authenticate as the user
user_conn = Connection(server, user=user_dn, password=password)
return user_conn.bind()
```
### 3. Group-Based Authorization
Check if user belongs to specific groups:
```python
def user_has_role(username, required_group):
server = Server('ldap://localhost:389')
conn = Connection(
server,
user='cn=admin,dc=testing,dc=local',
password='admin_password',
auto_bind=True
)
user_dn = f'uid={username},ou=people,dc=testing,dc=local'
conn.search(
'ou=groups,dc=testing,dc=local',
f'(&(objectClass=groupOfNames)(member={user_dn})(cn={required_group}))',
attributes=['cn']
)
return len(conn.entries) > 0
```
## Testing Your Integration
### 1. Start the LDAP Server
```bash
make start
```
### 2. Test Connection
```bash
python examples/simple_auth.py --list-users
```
### 3. Test Authentication
```bash
python examples/simple_auth.py --username jdoe --password password123
```
### 4. Test with Your Application
Point your application to:
- LDAP URL: `ldap://localhost:389`
- LDAPS URL: `ldaps://localhost:636` (with SSL)
- Base DN: `dc=testing,dc=local`
## Available Test Accounts
| Username | Password | Groups | Purpose |
|----------|----------|--------|---------|
| admin | password123 | admins | Administrative testing |
| jdoe | password123 | developers, users | Regular user testing |
| jsmith | password123 | developers, users | Regular user testing |
| testuser | password123 | users | Basic user testing |
## SSL/TLS Configuration
For production-like testing with LDAPS:
```python
import ssl
from ldap3 import Server, Connection, Tls
tls = Tls(
ca_certs_file='certs/ca.crt',
validate=ssl.CERT_REQUIRED
)
server = Server('ldaps://localhost:636', use_ssl=True, tls=tls)
conn = Connection(server, user=user_dn, password=password, auto_bind=True)
```
## Troubleshooting
### Connection Refused
```bash
# Check if LDAP server is running
make status
# Start if not running
make start
```
### Authentication Fails
```bash
# Verify user exists
make test-users
# Check LDAP logs
make logs
```
### Python ImportError
```bash
# Install ldap3 library
uv pip install ldap3
# or
pip install ldap3
```
## Additional Resources
- [ldap3 Documentation](https://ldap3.readthedocs.io/)
- [LDAP Protocol Overview](https://ldap.com/ldap-protocol/)
- [Django LDAP Authentication](https://django-auth-ldap.readthedocs.io/)
- [Flask-LDAP3-Login](https://flask-ldap3-login.readthedocs.io/)
## Contributing Examples
Have an example for a specific framework or use case? Contributions are welcome!
Examples we'd love to see:
- Express.js / Node.js authentication
- Ruby on Rails integration
- Go LDAP client
- Java Spring Security LDAP
- PHP authentication
- Docker Compose with application stack
Submit a pull request with your example!

288
examples/simple_auth.py Normal file
View File

@@ -0,0 +1,288 @@
#!/usr/bin/env python3
"""
Simple LDAP Authentication Example
This script demonstrates how to authenticate users against the LDAP server
and retrieve user information.
Usage:
python examples/simple_auth.py
python examples/simple_auth.py --username jdoe --password password123
"""
import argparse
import sys
from typing import Dict, List, Optional
try:
from ldap3 import ALL, Connection, Server
from ldap3.core.exceptions import LDAPException, LDAPBindError
except ImportError:
print("Error: ldap3 library not found.")
print("Install it with: uv pip install ldap3")
sys.exit(1)
# Configuration
LDAP_SERVER = "ldap://localhost:389"
LDAP_BASE_DN = "dc=testing,dc=local"
LDAP_PEOPLE_OU = "ou=people,dc=testing,dc=local"
LDAP_GROUPS_OU = "ou=groups,dc=testing,dc=local"
class LDAPAuthenticator:
"""Simple LDAP authentication helper."""
def __init__(self, server_url: str = LDAP_SERVER, base_dn: str = LDAP_BASE_DN):
"""Initialize the authenticator."""
self.server_url = server_url
self.base_dn = base_dn
self.server = Server(server_url, get_info=ALL)
def authenticate(self, username: str, password: str) -> bool:
"""
Authenticate a user with their username and password.
Args:
username: The user's uid (e.g., 'jdoe')
password: The user's password
Returns:
True if authentication successful, False otherwise
"""
# Construct the user's DN
user_dn = f"uid={username},{LDAP_PEOPLE_OU}"
try:
# Try to bind with the user's credentials
conn = Connection(self.server, user=user_dn, password=password)
if conn.bind():
print(f"✅ Authentication successful for user: {username}")
conn.unbind()
return True
else:
print(f"❌ Authentication failed for user: {username}")
return False
except LDAPBindError as e:
print(f"❌ Authentication failed: Invalid credentials")
return False
except LDAPException as e:
print(f"❌ LDAP error: {e}")
return False
except Exception as e:
print(f"❌ Unexpected error: {e}")
return False
def get_user_info(self, username: str, admin_dn: str, admin_password: str) -> Optional[Dict]:
"""
Retrieve detailed information about a user.
Args:
username: The user's uid
admin_dn: Admin DN for searching
admin_password: Admin password
Returns:
Dictionary with user information or None if not found
"""
try:
conn = Connection(self.server, user=admin_dn, password=admin_password, auto_bind=True)
# Search for the user
conn.search(
search_base=LDAP_PEOPLE_OU,
search_filter=f"(uid={username})",
attributes=["uid", "cn", "sn", "givenName", "mail", "uidNumber", "gidNumber"],
)
if conn.entries:
entry = conn.entries[0]
user_info = {
"username": str(entry.uid),
"full_name": str(entry.cn),
"first_name": str(entry.givenName) if entry.givenName else "",
"last_name": str(entry.sn),
"email": str(entry.mail),
"uid_number": int(entry.uidNumber) if entry.uidNumber else None,
"gid_number": int(entry.gidNumber) if entry.gidNumber else None,
"dn": entry.entry_dn,
}
conn.unbind()
return user_info
else:
print(f"User '{username}' not found")
conn.unbind()
return None
except LDAPException as e:
print(f"Error retrieving user info: {e}")
return None
def get_user_groups(self, username: str, admin_dn: str, admin_password: str) -> List[str]:
"""
Get all groups that a user belongs to.
Args:
username: The user's uid
admin_dn: Admin DN for searching
admin_password: Admin password
Returns:
List of group names
"""
try:
conn = Connection(self.server, user=admin_dn, password=admin_password, auto_bind=True)
# Get user's full DN first
user_dn = f"uid={username},{LDAP_PEOPLE_OU}"
# Search for groups that have this user as a member
conn.search(
search_base=LDAP_GROUPS_OU,
search_filter=f"(member={user_dn})",
attributes=["cn"],
)
groups = [str(entry.cn) for entry in conn.entries]
conn.unbind()
return groups
except LDAPException as e:
print(f"Error retrieving user groups: {e}")
return []
def list_all_users(self, admin_dn: str, admin_password: str) -> List[Dict]:
"""
List all users in the directory.
Args:
admin_dn: Admin DN for searching
admin_password: Admin password
Returns:
List of user dictionaries
"""
try:
conn = Connection(self.server, user=admin_dn, password=admin_password, auto_bind=True)
conn.search(
search_base=LDAP_PEOPLE_OU,
search_filter="(objectClass=inetOrgPerson)",
attributes=["uid", "cn", "mail"],
)
users = []
for entry in conn.entries:
users.append(
{
"username": str(entry.uid),
"full_name": str(entry.cn),
"email": str(entry.mail),
}
)
conn.unbind()
return users
except LDAPException as e:
print(f"Error listing users: {e}")
return []
def print_user_info(user_info: Dict):
"""Pretty print user information."""
print("\n" + "=" * 50)
print("USER INFORMATION")
print("=" * 50)
print(f"Username: {user_info['username']}")
print(f"Full Name: {user_info['full_name']}")
print(f"First Name: {user_info['first_name']}")
print(f"Last Name: {user_info['last_name']}")
print(f"Email: {user_info['email']}")
print(f"UID Number: {user_info['uid_number']}")
print(f"GID Number: {user_info['gid_number']}")
print(f"DN: {user_info['dn']}")
print("=" * 50 + "\n")
def main():
"""Main function demonstrating LDAP authentication."""
parser = argparse.ArgumentParser(description="LDAP Authentication Example")
parser.add_argument(
"--username", "-u", default="jdoe", help="Username to authenticate (default: jdoe)"
)
parser.add_argument(
"--password", "-p", default="password123", help="Password (default: password123)"
)
parser.add_argument(
"--server", "-s", default=LDAP_SERVER, help=f"LDAP server URL (default: {LDAP_SERVER})"
)
parser.add_argument("--list-users", action="store_true", help="List all users")
args = parser.parse_args()
# Admin credentials for retrieving user info
admin_dn = "cn=admin,dc=testing,dc=local"
admin_password = "admin_password"
print(f"\n🔐 LDAP Authentication Example")
print(f"Server: {args.server}\n")
# Initialize authenticator
auth = LDAPAuthenticator(server_url=args.server)
# List all users if requested
if args.list_users:
print("📋 Listing all users...")
users = auth.list_all_users(admin_dn, admin_password)
if users:
print(f"\nFound {len(users)} user(s):\n")
for user in users:
print(f"{user['username']:12s} - {user['full_name']:20s} ({user['email']})")
else:
print("No users found")
print()
return
# Authenticate user
print(f"Attempting to authenticate user: {args.username}")
if auth.authenticate(args.username, args.password):
print("✅ Authentication successful!\n")
# Get detailed user information
print("Fetching user information...")
user_info = auth.get_user_info(args.username, admin_dn, admin_password)
if user_info:
print_user_info(user_info)
# Get user's groups
print("Fetching user groups...")
groups = auth.get_user_groups(args.username, admin_dn, admin_password)
if groups:
print(f"User belongs to {len(groups)} group(s):")
for group in groups:
print(f"{group}")
else:
print("User is not a member of any groups")
print()
else:
print("❌ Authentication failed!")
print("\nAvailable test users:")
print(" • jdoe (password: password123)")
print(" • jsmith (password: password123)")
print(" • testuser (password: password123)")
print(" • admin (password: password123)")
sys.exit(1)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nInterrupted by user")
sys.exit(0)
except Exception as e:
print(f"\nError: {e}")
sys.exit(1)