0
# Basic Authentication
1
2
HTTP Basic authentication implementation providing username/password authentication with secure password verification and hashing support. Basic auth transmits credentials in Base64-encoded format and is suitable for HTTPS environments.
3
4
## Capabilities
5
6
### HTTPBasicAuth Class
7
8
Creates an HTTP Basic authentication handler with customizable verification callbacks and password hashing support.
9
10
```python { .api }
11
class HTTPBasicAuth(HTTPAuth):
12
def __init__(self, scheme=None, realm=None):
13
"""
14
Initialize Basic authentication handler.
15
16
Parameters:
17
- scheme (str, optional): Authentication scheme, defaults to 'Basic'
18
- realm (str, optional): Authentication realm, defaults to 'Authentication Required'
19
"""
20
```
21
22
### Password Verification
23
24
Register callback functions for password verification, supporting both plain password and hashed password workflows.
25
26
```python { .api }
27
def verify_password(self, f):
28
"""
29
Decorator to register password verification callback.
30
31
Parameters:
32
- f (function): Callback function(username, password) -> user_object or None
33
34
Returns:
35
The decorated function
36
37
Usage:
38
@auth.verify_password
39
def verify_password(username, password):
40
# Verify credentials and return user object if valid
41
return user if valid else None
42
"""
43
44
def hash_password(self, f):
45
"""
46
Decorator to register password hashing callback.
47
48
Parameters:
49
- f (function): Callback function(password) -> hashed_password or function(username, password) -> hashed_password
50
51
Returns:
52
The decorated function
53
54
Usage:
55
@auth.hash_password
56
def hash_password(password):
57
return generate_password_hash(password)
58
"""
59
```
60
61
### Route Protection
62
63
Protect Flask routes with Basic authentication using the login_required decorator.
64
65
```python { .api }
66
def login_required(self, f=None, role=None, optional=None):
67
"""
68
Decorator to require authentication for Flask routes.
69
70
Parameters:
71
- f (function, optional): Flask route function to protect
72
- role (str|list, optional): Required user role(s)
73
- optional (bool, optional): Make authentication optional
74
75
Returns:
76
Decorated function or decorator
77
78
Usage:
79
@auth.login_required
80
def protected_route():
81
return f"Hello {auth.current_user()}"
82
83
@auth.login_required(role='admin')
84
def admin_route():
85
return "Admin only"
86
"""
87
```
88
89
### User Information
90
91
Access current authenticated user information within protected routes.
92
93
```python { .api }
94
def current_user(self):
95
"""
96
Get current authenticated user object.
97
98
Returns:
99
User object returned by verify_password callback, or None if not authenticated
100
"""
101
102
def username(self):
103
"""
104
Get current authenticated username.
105
106
Returns:
107
str: Username from authentication credentials, or empty string if not authenticated
108
"""
109
```
110
111
## Usage Examples
112
113
### Basic Password Verification
114
115
```python
116
from flask import Flask
117
from flask_httpauth import HTTPBasicAuth
118
119
app = Flask(__name__)
120
auth = HTTPBasicAuth()
121
122
users = {
123
"john": "hello",
124
"susan": "bye"
125
}
126
127
@auth.verify_password
128
def verify_password(username, password):
129
if username in users and users[username] == password:
130
return username
131
132
@app.route('/')
133
@auth.login_required
134
def index():
135
return f"Hello, {auth.current_user()}"
136
```
137
138
### Hashed Password Storage
139
140
```python
141
from flask import Flask
142
from flask_httpauth import HTTPBasicAuth
143
from werkzeug.security import generate_password_hash, check_password_hash
144
145
app = Flask(__name__)
146
auth = HTTPBasicAuth()
147
148
users = {
149
"john": generate_password_hash("hello"),
150
"susan": generate_password_hash("bye")
151
}
152
153
@auth.verify_password
154
def verify_password(username, password):
155
if username in users and check_password_hash(users.get(username), password):
156
return username
157
158
@app.route('/')
159
@auth.login_required
160
def index():
161
return f"Hello, {auth.current_user()}"
162
```
163
164
### Custom Password Hashing
165
166
```python
167
from flask import Flask
168
from flask_httpauth import HTTPBasicAuth
169
import hashlib
170
171
app = Flask(__name__)
172
auth = HTTPBasicAuth()
173
174
@auth.hash_password
175
def hash_password(password):
176
return hashlib.md5(password.encode('utf-8')).hexdigest()
177
178
@auth.verify_password
179
def verify_password(username, password):
180
# Password is automatically hashed before verification
181
stored_password = get_password_hash(username)
182
return username if stored_password else None
183
```
184
185
## Error Handling
186
187
Basic authentication automatically handles authentication errors with appropriate HTTP status codes:
188
189
- **401 Unauthorized**: Invalid credentials or missing authentication
190
- **403 Forbidden**: Valid credentials but insufficient role permissions
191
- **WWW-Authenticate header**: Automatically added with realm information
192
193
Custom error handling can be implemented using the `error_handler` decorator inherited from the base HTTPAuth class.