0
# User Authentication
1
2
Authentication decorators, login/logout functions, session management, and access control mechanisms for protecting routes and resources in Flask applications.
3
4
## Capabilities
5
6
### Authentication Decorators
7
8
Decorators for protecting routes and requiring user authentication with various methods and flexibility.
9
10
```python { .api }
11
def auth_required(*auth_methods):
12
"""
13
Flexible authentication decorator supporting multiple authentication mechanisms.
14
15
Parameters:
16
- auth_methods: Tuple of authentication methods ('session', 'token', 'basic')
17
If empty, uses configured default methods
18
19
Returns:
20
Decorator function that enforces authentication
21
"""
22
23
def login_required(func):
24
"""
25
Decorator requiring user to be logged in via session authentication.
26
Legacy wrapper around auth_required().
27
28
Parameters:
29
- func: Function to decorate
30
31
Returns:
32
Decorated function that requires login
33
"""
34
35
def auth_token_required(func):
36
"""
37
Decorator requiring API token authentication.
38
39
Parameters:
40
- func: Function to decorate
41
42
Returns:
43
Decorated function that requires valid auth token
44
"""
45
46
def http_auth_required(func):
47
"""
48
Decorator requiring HTTP basic authentication.
49
50
Parameters:
51
- func: Function to decorate
52
53
Returns:
54
Decorated function that requires HTTP basic auth
55
"""
56
57
def anonymous_user_required(func):
58
"""
59
Decorator requiring user to be anonymous (not authenticated).
60
61
Parameters:
62
- func: Function to decorate
63
64
Returns:
65
Decorated function that requires anonymous user
66
"""
67
```
68
69
### Login and Logout Functions
70
71
Core functions for managing user authentication sessions and login state.
72
73
```python { .api }
74
def login_user(user, remember=False, duration=None, force=False, fresh=True):
75
"""
76
Log in a user with session management.
77
78
Parameters:
79
- user: User object to log in
80
- remember: Whether to set remember-me cookie (default: False)
81
- duration: Duration for remember-me cookie (default: None)
82
- force: Force login even if user is inactive (default: False)
83
- fresh: Mark authentication as fresh (default: True)
84
85
Returns:
86
True if login successful, False otherwise
87
"""
88
89
def logout_user():
90
"""
91
Log out the current user by clearing session data.
92
93
Returns:
94
True if logout successful, False otherwise
95
"""
96
```
97
98
### Authentication Freshness
99
100
Functions for managing authentication freshness requirements for sensitive operations.
101
102
```python { .api }
103
def check_and_update_authn_fresh(within, grace=None):
104
"""
105
Check if current authentication is fresh and update if needed.
106
107
Parameters:
108
- within: Time period (timedelta) within which auth must be fresh
109
- grace: Grace period for allowing stale authentication (default: None)
110
111
Returns:
112
Tuple of (is_fresh: bool, is_grace: bool)
113
"""
114
```
115
116
### Password Verification
117
118
Functions for verifying user passwords against stored hashes.
119
120
```python { .api }
121
def verify_password(password, password_hash):
122
"""
123
Verify a password against its hash.
124
125
Parameters:
126
- password: Plain text password to verify
127
- password_hash: Stored password hash to verify against
128
129
Returns:
130
True if password matches hash, False otherwise
131
"""
132
133
def verify_and_update_password(password, user):
134
"""
135
Verify password and update hash if needed (e.g., algorithm upgrade).
136
137
Parameters:
138
- password: Plain text password to verify
139
- user: User object with password hash
140
141
Returns:
142
True if password matches, False otherwise
143
"""
144
```
145
146
### Identity Lookup
147
148
Functions for finding users by various identity attributes.
149
150
```python { .api }
151
def lookup_identity(identity):
152
"""
153
Look up user by identity (email, username, or other configured attribute).
154
155
Parameters:
156
- identity: Identity string to search for
157
158
Returns:
159
User object if found, None otherwise
160
"""
161
```
162
163
### Authentication Handler Functions
164
165
Default handler functions for various authentication scenarios that can be customized.
166
167
```python { .api }
168
def default_unauthn_handler(mechanisms, headers=None):
169
"""
170
Default handler for unauthenticated requests.
171
172
Parameters:
173
- mechanisms: List of available authentication mechanisms
174
- headers: Additional headers to include in response
175
176
Returns:
177
Flask response for unauthenticated request
178
"""
179
180
def default_reauthn_handler(within, grace):
181
"""
182
Default handler for re-authentication requirements.
183
184
Parameters:
185
- within: Required freshness period
186
- grace: Grace period for stale authentication
187
188
Returns:
189
Flask response for re-authentication request
190
"""
191
192
def default_unauthz_handler():
193
"""
194
Default handler for unauthorized access attempts.
195
196
Returns:
197
Flask response for unauthorized request
198
"""
199
```
200
201
### Authentication Forms
202
203
Core form for user login and authentication.
204
205
```python { .api }
206
class LoginForm(Form):
207
"""
208
User login form with email/username and password fields.
209
210
Fields:
211
- email: Email or username field (identity)
212
- password: Password field
213
- remember: Remember me checkbox (optional)
214
- next: Next URL hidden field
215
"""
216
email: StringField
217
password: PasswordField
218
remember: BooleanField
219
next: HiddenField
220
221
class VerifyForm(Form):
222
"""
223
Password verification form for sensitive operations.
224
225
Fields:
226
- password: Password field for verification
227
"""
228
password: PasswordField
229
230
class PasswordlessLoginForm(Form):
231
"""
232
Passwordless authentication form.
233
234
Fields:
235
- user: Email or username field
236
"""
237
user: StringField
238
```
239
240
## Authentication Mechanisms
241
242
Flask-Security supports multiple authentication mechanisms that can be used individually or in combination:
243
244
### Session Authentication
245
- Traditional cookie-based session authentication
246
- Integrates with Flask-Login for session management
247
- Supports remember-me functionality
248
- Default mechanism for web applications
249
250
### Token Authentication
251
- API token-based authentication
252
- Tokens can be passed via query parameter, form data, or headers
253
- Suitable for API endpoints and mobile applications
254
- Tokens can have expiration times
255
256
### HTTP Basic Authentication
257
- Standard HTTP Basic Auth using Authorization header
258
- Useful for API endpoints and simple authentication
259
- Username/password sent with each request
260
261
## Usage Examples
262
263
### Basic Route Protection
264
265
```python
266
from flask_security import login_required, auth_required, current_user
267
268
@app.route('/profile')
269
@login_required
270
def profile():
271
return f"Hello {current_user.email}!"
272
273
@app.route('/api/data')
274
@auth_required('token')
275
def api_data():
276
return {"data": "sensitive information"}
277
278
@app.route('/admin')
279
@auth_required('session', 'token')
280
def admin():
281
return "Admin panel"
282
```
283
284
### Custom Authentication Logic
285
286
```python
287
from flask_security import login_user, logout_user, verify_password, lookup_identity
288
289
@app.route('/custom-login', methods=['POST'])
290
def custom_login():
291
email = request.form.get('email')
292
password = request.form.get('password')
293
294
user = lookup_identity(email)
295
if user and verify_password(password, user.password):
296
login_user(user, remember=True)
297
return redirect('/dashboard')
298
else:
299
flash('Invalid credentials')
300
return redirect('/login')
301
302
@app.route('/custom-logout')
303
def custom_logout():
304
logout_user()
305
return redirect('/')
306
```
307
308
### Authentication Freshness Check
309
310
```python
311
from datetime import timedelta
312
from flask_security import check_and_update_authn_fresh
313
314
@app.route('/sensitive-operation')
315
@login_required
316
def sensitive_operation():
317
# Require authentication within last 10 minutes
318
is_fresh, is_grace = check_and_update_authn_fresh(
319
within=timedelta(minutes=10)
320
)
321
322
if not is_fresh:
323
return redirect(url_for_security('verify'))
324
325
return "Performing sensitive operation"
326
```
327
328
### Passwordless Authentication
329
330
```python
331
from flask_security import send_login_instructions
332
333
@app.route('/passwordless-login', methods=['POST'])
334
def passwordless_login():
335
email = request.form.get('email')
336
user = lookup_identity(email)
337
338
if user:
339
send_login_instructions(user)
340
flash('Login instructions sent to your email')
341
342
return redirect('/login')
343
```