-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic_auth_http_server.py
More file actions
231 lines (191 loc) · 7.6 KB
/
Copy pathbasic_auth_http_server.py
File metadata and controls
231 lines (191 loc) · 7.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#
# Copyright (C) 2025 pdnguyen of HCMC University of Technology VNU-HCM.
# All rights reserved.
# This file is part of the CO3093/CO3094 course.
#
# WeApRous release - Basic Authentication Demo
#
# The authors hereby grant to Licensee personal permission to use
# and modify the Licensed Source Code for the sole purpose of studying
# while attending the course
#
"""
Basic Authentication HTTP Server Demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This server demonstrates HTTP Basic Authentication using the WeApRous framework.
Unlike session-based authentication, Basic Auth uses the browser's built-in popup
and sends credentials with every request.
Features:
- HTTP Basic Authentication with browser popup
- Multiple authentication realms
- Protected routes with different credential requirements
- Fallback to static file serving for unprotected content
Usage:
python basic_auth_http_server.py
Test URLs:
- http://127.0.0.1:9000/ # Public access
- http://127.0.0.1:9000/admin # Requires admin:123
- http://127.0.0.1:9000/api/data # Requires user:pass or admin:123
- http://127.0.0.1:9000/secure # Requires secure:key456
"""
import socket
import threading
import os
import argparse
from daemon import create_backend
from daemon.response import Response
def load_template(template_path, **kwargs):
"""
Load HTML template from www directory and replace placeholders.
:param template_path (str): Path to template file in www directory
:param kwargs: Key-value pairs for template replacement
:return str: Rendered HTML content
"""
try:
# Nếu template_path là admin.html, public.html, secure.html thì lấy từ www/basic_auth
basic_auth_files = {"admin.html", "public.html", "secure.html"}
if template_path in basic_auth_files:
file_path = os.path.join('www', 'basic_auth', template_path)
else:
file_path = os.path.join('www', template_path)
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Replace placeholders ({{KEY}} format)
for key, value in kwargs.items():
placeholder = "{{" + key.upper() + "}}"
content = content.replace(placeholder, str(value))
return content
except Exception as e:
print("[Template] Error loading {}: {}".format(template_path, e))
return "<h1>Template Error</h1><p>Could not load template: {}</p>".format(template_path)
# Basic Auth credentials for different realms
BASIC_AUTH_CREDENTIALS = {
"Admin Area": {
"admin": "123"
},
"API Access": {
"user": "pass",
"admin": "123"
},
"Secure Zone": {
"secure": "key456"
}
}
def require_basic_auth(realm="WeApRous", credentials=None):
"""
Decorator for routes that require HTTP Basic Authentication.
:param realm (str): Authentication realm name
:param credentials (dict): Valid username:password pairs
:return: Decorator function
"""
if credentials is None:
credentials = {"admin": "123"} # Default credentials
def decorator(handler_func):
def wrapper(request):
# Check Basic Auth credentials
username = getattr(request, 'basic_auth_username', None)
password = getattr(request, 'basic_auth_password', None)
if username and password and credentials.get(username) == password:
print("[BasicAuth] Authentication successful for user: {}".format(username))
# Add user info to request for handler use
request.authenticated_user = username
request.auth_method = 'basic'
request.auth_realm = realm
return handler_func(request)
else:
print("[BasicAuth] Authentication failed or missing - sending challenge for realm: {}".format(realm))
resp = Response()
return resp.build_unauthorized_basic(realm=realm)
return wrapper
return decorator
# Route handlers
def public_page(request):
"""Public page - no authentication required"""
html_content = load_template('public.html')
# Use Response object directly
resp = Response()
return resp.build_success_response(html_content, "text/html; charset=utf-8")
@require_basic_auth(realm="Admin Area", credentials=BASIC_AUTH_CREDENTIALS["Admin Area"])
def admin_area(request):
"""Admin area - requires admin credentials"""
user = request.authenticated_user
realm = request.auth_realm
html_content = load_template('admin.html', user=user, realm=realm)
# Use Response object directly
resp = Response()
return resp.build_success_response(html_content, "text/html; charset=utf-8")
@require_basic_auth(realm="API Access", credentials=BASIC_AUTH_CREDENTIALS["API Access"])
def api_data(request):
"""API endpoint - supports multiple user credentials"""
user = request.authenticated_user
realm = request.auth_realm
# Create JSON data
data = {
"status": "success",
"user": user,
"realm": realm,
"auth_method": "basic",
"data": ["item1", "item2", "item3"]
}
# Use Response object directly for JSON
resp = Response()
return resp.build_json_response(data)
@require_basic_auth(realm="Secure Zone", credentials=BASIC_AUTH_CREDENTIALS["Secure Zone"])
def secure_zone(request):
"""Secure area with different credentials"""
user = request.authenticated_user
realm = request.auth_realm
html_content = load_template('secure.html', user=user, realm=realm)
# Use Response object directly
resp = Response()
return resp.build_success_response(html_content, "text/html; charset=utf-8")
# Route mapping
routes = {
('GET', '/'): public_page,
('GET', '/index.html'): public_page,
('GET', '/admin'): admin_area,
('GET', '/api/data'): api_data,
('GET', '/secure'): secure_zone,
}
if __name__ == '__main__':
"""
Entry point for launching the Basic Auth HTTP server.
Uses WeApRous framework infrastructure instead of manual socket handling.
"""
parser = argparse.ArgumentParser(
prog='BasicAuthServer',
description='WeApRous Basic Auth HTTP Server Demo'
)
parser.add_argument(
'--server-ip',
type=str,
default='127.0.0.1',
help='IP address to bind the server (default: 127.0.0.1)'
)
parser.add_argument(
'--server-port',
type=int,
default=9000,
help='Port number to bind the server (default: 9000)'
)
args = parser.parse_args()
print("=" * 60)
print("🔐 WeApRous Basic Auth HTTP Server")
print("=" * 60)
print("Server running on: http://{}:{}/".format(args.server_ip, args.server_port))
print("")
print("Test Credentials:")
print(" Admin Area: admin / 123")
print(" API Access: user / pass OR admin / 123")
print(" Secure Zone: secure / key456")
print("")
print("Test URLs:")
print(" • http://{}:{}/ - Public page".format(args.server_ip, args.server_port))
print(" • http://{}:{}/admin - Admin area (popup login)".format(args.server_ip, args.server_port))
print(" • http://{}:{}/api/data - API endpoint (popup login)".format(args.server_ip, args.server_port))
print(" • http://{}:{}/secure - Secure zone (popup login)".format(args.server_ip, args.server_port))
print("")
print("Press Ctrl+C to stop...")
print("=" * 60)
# Use WeApRous framework infrastructure
create_backend(args.server_ip, args.server_port, routes)