0
# Authentication System
1
2
Django's authentication system provides user management, permissions, groups, and session-based authentication with customizable backends and password validation.
3
4
## Capabilities
5
6
### Authentication Functions
7
8
Core functions for user authentication and session management.
9
10
```python { .api }
11
def authenticate(request: HttpRequest = None, **credentials) -> Optional[User]:
12
"""
13
Verify user credentials against authentication backends.
14
15
Args:
16
request: HTTP request object (optional)
17
**credentials: Authentication credentials (username, password, etc.)
18
19
Returns:
20
Authenticated user object or None if authentication fails
21
"""
22
23
def login(request: HttpRequest, user: AbstractBaseUser, backend: str = None) -> None:
24
"""
25
Log user into current session.
26
27
Args:
28
request: HTTP request object
29
user: User object to authenticate
30
backend: Authentication backend used (optional)
31
"""
32
33
def logout(request: HttpRequest) -> None:
34
"""
35
Log user out of current session.
36
37
Args:
38
request: HTTP request object
39
"""
40
41
def get_user_model() -> Type[AbstractBaseUser]:
42
"""
43
Get the active user model for the current Django project.
44
45
Returns:
46
User model class
47
"""
48
49
def get_user(request: HttpRequest) -> Union[AbstractBaseUser, AnonymousUser]:
50
"""
51
Get user from request session.
52
53
Args:
54
request: HTTP request object
55
56
Returns:
57
User object or AnonymousUser if not authenticated
58
"""
59
60
def update_session_auth_hash(request: HttpRequest, user: AbstractBaseUser) -> None:
61
"""
62
Update session authentication hash after password change.
63
64
Args:
65
request: HTTP request object
66
user: User with updated password
67
"""
68
```
69
70
### User Models
71
72
User model classes and authentication interfaces.
73
74
```python { .api }
75
class AbstractBaseUser(models.Model):
76
"""
77
Base user model providing core authentication functionality.
78
79
Abstract base class with password management and authentication interface.
80
"""
81
password: models.CharField
82
last_login: models.DateTimeField
83
84
is_active: bool = True
85
86
USERNAME_FIELD: str = 'username'
87
EMAIL_FIELD: str = 'email'
88
REQUIRED_FIELDS: list = []
89
90
def set_password(self, raw_password: str) -> None: ...
91
def check_password(self, raw_password: str) -> bool: ...
92
def set_unusable_password(self) -> None: ...
93
def has_usable_password(self) -> bool: ...
94
def get_session_auth_hash(self) -> str: ...
95
def get_username(self) -> str: ...
96
def clean(self) -> None: ...
97
def natural_key(self) -> tuple: ...
98
def is_anonymous(self) -> bool: ...
99
def is_authenticated(self) -> bool: ...
100
def get_full_name(self) -> str: ...
101
def get_short_name(self) -> str: ...
102
103
class AbstractUser(AbstractBaseUser, PermissionsMixin):
104
"""
105
Complete user model with username and permission support.
106
107
Full-featured user model with built-in fields and permission system.
108
"""
109
username: models.CharField
110
first_name: models.CharField
111
last_name: models.CharField
112
email: models.EmailField
113
is_staff: models.BooleanField
114
is_active: models.BooleanField
115
date_joined: models.DateTimeField
116
117
objects: BaseUserManager
118
119
USERNAME_FIELD: str = 'username'
120
EMAIL_FIELD: str = 'email'
121
REQUIRED_FIELDS: list = ['email']
122
123
def clean(self) -> None: ...
124
def get_full_name(self) -> str: ...
125
def get_short_name(self) -> str: ...
126
def email_user(self, subject: str, message: str, from_email: str = None, **kwargs) -> None: ...
127
128
class User(AbstractUser):
129
"""
130
Default Django user model.
131
132
Ready-to-use user model with all standard fields and functionality.
133
"""
134
135
class AnonymousUser:
136
"""
137
User object representing unauthenticated visitors.
138
139
Provides consistent interface for anonymous users.
140
"""
141
id: None = None
142
pk: None = None
143
username: str = ''
144
is_staff: bool = False
145
is_active: bool = False
146
is_superuser: bool = False
147
148
def __str__(self) -> str: ...
149
def __eq__(self, other) -> bool: ...
150
def __hash__(self) -> int: ...
151
def save(self) -> None: ...
152
def delete(self) -> None: ...
153
def set_password(self, raw_password: str) -> None: ...
154
def check_password(self, raw_password: str) -> bool: ...
155
def is_anonymous(self) -> bool: ...
156
def is_authenticated(self) -> bool: ...
157
def get_username(self) -> str: ...
158
def get_user_permissions(self, obj=None) -> set: ...
159
def get_all_permissions(self, obj=None) -> set: ...
160
def get_group_permissions(self, obj=None) -> set: ...
161
def has_perm(self, perm: str, obj=None) -> bool: ...
162
def has_perms(self, perm_list: list, obj=None) -> bool: ...
163
def has_module_perms(self, module: str) -> bool: ...
164
```
165
166
### User Managers
167
168
Manager classes for user model database operations.
169
170
```python { .api }
171
class BaseUserManager(models.Manager):
172
"""
173
Base manager for user models with authentication support.
174
175
Provides user creation methods and authentication utilities.
176
"""
177
def make_random_password(self, length: int = 10, allowed_chars: str = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') -> str: ...
178
def get_by_natural_key(self, username: str): ...
179
def create_user(self, username: str, email: str = None, password: str = None, **extra_fields): ...
180
def create_superuser(self, username: str, email: str = None, password: str = None, **extra_fields): ...
181
def with_perm(self, perm: str, is_active: bool = True, include_superusers: bool = True, backend: str = None, obj=None): ...
182
183
class UserManager(BaseUserManager):
184
"""
185
Manager for Django's built-in User model.
186
187
Extends BaseUserManager with email-based user creation.
188
"""
189
def _create_user(self, username: str, email: str, password: str, **extra_fields): ...
190
def create_user(self, username: str, email: str = '', password: str = None, **extra_fields): ...
191
def create_superuser(self, username: str, email: str = None, password: str = None, **extra_fields): ...
192
```
193
194
### Permission System
195
196
Classes and functions for managing user permissions and authorization.
197
198
```python { .api }
199
class Permission(models.Model):
200
"""
201
Individual permission that can be granted to users or groups.
202
203
Represents a specific permission with content type and codename.
204
"""
205
name: models.CharField
206
content_type: models.ForeignKey
207
codename: models.CharField
208
209
objects: models.Manager
210
211
def __str__(self) -> str: ...
212
def natural_key(self) -> tuple: ...
213
214
class Group(models.Model):
215
"""
216
User group for organizing permissions.
217
218
Groups allow batch permission assignment to multiple users.
219
"""
220
name: models.CharField
221
permissions: models.ManyToManyField
222
223
objects: models.Manager
224
225
def __str__(self) -> str: ...
226
def natural_key(self) -> tuple: ...
227
228
class PermissionsMixin(models.Model):
229
"""
230
Mixin adding permission functionality to user models.
231
232
Provides permission checking and group membership methods.
233
"""
234
is_superuser: models.BooleanField
235
groups: models.ManyToManyField
236
user_permissions: models.ManyToManyField
237
238
def get_user_permissions(self, obj=None) -> set: ...
239
def get_group_permissions(self, obj=None) -> set: ...
240
def get_all_permissions(self, obj=None) -> set: ...
241
def has_perm(self, perm: str, obj=None) -> bool: ...
242
def has_perms(self, perm_list: list, obj=None) -> bool: ...
243
def has_module_perms(self, app_label: str) -> bool: ...
244
245
def get_permission_codename(action: str, opts) -> str:
246
"""
247
Generate permission codename for model action.
248
249
Args:
250
action: Permission action (add, change, delete, view)
251
opts: Model meta options
252
253
Returns:
254
Permission codename string
255
"""
256
```
257
258
### Authentication Backends
259
260
Backend classes for customizing authentication logic.
261
262
```python { .api }
263
class BaseBackend:
264
"""
265
Base authentication backend interface.
266
267
Abstract base class for implementing custom authentication.
268
"""
269
def authenticate(self, request: HttpRequest, **credentials): ...
270
def get_user(self, user_id: int): ...
271
def get_user_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
272
def get_group_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
273
def get_all_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
274
def has_perm(self, user_obj: AbstractBaseUser, perm: str, obj=None) -> bool: ...
275
def has_module_perms(self, user_obj: AbstractBaseUser, app_label: str) -> bool: ...
276
def with_perm(self, perm: str, is_active: bool = True, include_superusers: bool = True, obj=None): ...
277
278
class ModelBackend(BaseBackend):
279
"""
280
Default Django authentication backend.
281
282
Authenticates against Django user model with username/password.
283
"""
284
def authenticate(self, request: HttpRequest, username: str = None, password: str = None, **kwargs): ...
285
def user_can_authenticate(self, user: AbstractBaseUser) -> bool: ...
286
def _get_user_permissions(self, user_obj: AbstractBaseUser) -> set: ...
287
def _get_group_permissions(self, user_obj: AbstractBaseUser) -> set: ...
288
def _get_permissions(self, user_obj: AbstractBaseUser, obj, from_name: str) -> set: ...
289
def get_user_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
290
def get_group_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
291
def get_all_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
292
def has_perm(self, user_obj: AbstractBaseUser, perm: str, obj=None) -> bool: ...
293
def has_module_perms(self, user_obj: AbstractBaseUser, app_label: str) -> bool: ...
294
def with_perm(self, perm: str, is_active: bool = True, include_superusers: bool = True, obj=None): ...
295
def get_user(self, user_id: int): ...
296
297
class AllowAllUsersModelBackend(ModelBackend):
298
"""
299
Authentication backend allowing inactive users.
300
301
Similar to ModelBackend but doesn't check is_active flag.
302
"""
303
def user_can_authenticate(self, user: AbstractBaseUser) -> bool: ...
304
305
class RemoteUserBackend(ModelBackend):
306
"""
307
Backend for remote user authentication (e.g., web server auth).
308
309
Authenticates users based on REMOTE_USER header.
310
"""
311
create_unknown_user: bool = True
312
313
def authenticate(self, request: HttpRequest, remote_user: str): ...
314
def clean_username(self, username: str) -> str: ...
315
def configure_user(self, request: HttpRequest, user: AbstractBaseUser, created: bool = True): ...
316
def user_can_authenticate(self, user: AbstractBaseUser) -> bool: ...
317
318
def get_backends() -> list:
319
"""
320
Get list of configured authentication backends.
321
322
Returns:
323
List of authentication backend instances
324
"""
325
326
def load_backend(path: str) -> BaseBackend:
327
"""
328
Load authentication backend by dotted path.
329
330
Args:
331
path: Dotted path to backend class
332
333
Returns:
334
Backend instance
335
"""
336
```
337
338
### Password Validation
339
340
Password strength validation and policy enforcement.
341
342
```python { .api }
343
def validate_password(password: str, user: AbstractBaseUser = None, password_validators: list = None) -> None:
344
"""
345
Validate password against configured validators.
346
347
Args:
348
password: Password to validate
349
user: User object for context (optional)
350
password_validators: List of validator instances (optional)
351
352
Raises:
353
ValidationError: If password validation fails
354
"""
355
356
def password_changed(password: str, user: AbstractBaseUser = None, password_validators: list = None) -> None:
357
"""
358
Inform validators that password has been changed.
359
360
Args:
361
password: New password
362
user: User object (optional)
363
password_validators: List of validator instances (optional)
364
"""
365
366
def password_validators_help_texts(password_validators: list = None) -> list:
367
"""
368
Get help texts from password validators.
369
370
Args:
371
password_validators: List of validator instances (optional)
372
373
Returns:
374
List of help text strings
375
"""
376
377
def password_validators_help_text_html(password_validators: list = None) -> str:
378
"""
379
Get HTML formatted help text from password validators.
380
381
Args:
382
password_validators: List of validator instances (optional)
383
384
Returns:
385
HTML formatted help text
386
"""
387
388
class CommonPasswordValidator:
389
"""
390
Password validator that rejects common passwords.
391
392
Validates against list of common passwords from database.
393
"""
394
DEFAULT_PASSWORD_LIST_PATH: str
395
396
def __init__(self, password_list_path: str = None): ...
397
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
398
def get_help_text(self) -> str: ...
399
400
class MinimumLengthValidator:
401
"""
402
Password validator enforcing minimum length requirement.
403
"""
404
def __init__(self, min_length: int = 8): ...
405
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
406
def get_help_text(self) -> str: ...
407
408
class AttributeSimilarityValidator:
409
"""
410
Password validator preventing passwords similar to user attributes.
411
"""
412
DEFAULT_USER_ATTRIBUTES: tuple = ('username', 'first_name', 'last_name', 'email')
413
414
def __init__(self, user_attributes: tuple = None, max_similarity: float = 0.7): ...
415
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
416
def get_help_text(self) -> str: ...
417
418
class NumericPasswordValidator:
419
"""
420
Password validator rejecting entirely numeric passwords.
421
"""
422
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
423
def get_help_text(self) -> str: ...
424
```
425
426
### Password Hashers
427
428
Classes for password hashing and verification.
429
430
```python { .api }
431
class BasePasswordHasher:
432
"""
433
Base password hasher interface.
434
435
Abstract base class for implementing password hashing algorithms.
436
"""
437
algorithm: str = None
438
library: str = None
439
440
def encode(self, password: str, salt: str) -> str: ...
441
def verify(self, password: str, encoded: str) -> bool: ...
442
def safe_summary(self, encoded: str) -> dict: ...
443
def harden_runtime(self, password: str, encoded: str) -> None: ...
444
def must_update(self, encoded: str) -> bool: ...
445
446
def check_password(password: str, encoded: str, setter=None, preferred: str = 'default') -> bool:
447
"""
448
Check password against encoded hash.
449
450
Args:
451
password: Raw password to check
452
encoded: Encoded password hash
453
setter: Function to update hash if needed
454
preferred: Preferred hasher algorithm
455
456
Returns:
457
True if password matches hash
458
"""
459
460
def make_password(password: str, salt: str = None, hasher: str = 'default') -> str:
461
"""
462
Hash password with salt using specified algorithm.
463
464
Args:
465
password: Raw password to hash
466
salt: Salt for hashing (generated if None)
467
hasher: Hasher algorithm name
468
469
Returns:
470
Encoded password hash
471
"""
472
473
def is_password_usable(encoded: str) -> bool:
474
"""
475
Check if password hash is usable for authentication.
476
477
Args:
478
encoded: Password hash
479
480
Returns:
481
True if hash is usable
482
"""
483
484
def identify_hasher(encoded: str) -> BasePasswordHasher:
485
"""
486
Identify hasher used for encoded password.
487
488
Args:
489
encoded: Password hash
490
491
Returns:
492
Hasher instance for the algorithm
493
"""
494
```
495
496
### Authentication Decorators
497
498
Decorators for protecting views with authentication requirements.
499
500
```python { .api }
501
def login_required(function=None, redirect_field_name: str = 'next', login_url: str = None):
502
"""
503
Decorator requiring user authentication for view access.
504
505
Args:
506
function: View function to protect
507
redirect_field_name: URL parameter for redirect after login
508
login_url: Login page URL
509
510
Returns:
511
Decorated view function
512
"""
513
514
def permission_required(perm: str, login_url: str = None, raise_exception: bool = False):
515
"""
516
Decorator requiring specific permission for view access.
517
518
Args:
519
perm: Required permission string
520
login_url: Login page URL
521
raise_exception: Raise PermissionDenied instead of redirect
522
523
Returns:
524
Decorator function
525
"""
526
527
def user_passes_test(test_func, login_url: str = None, redirect_field_name: str = 'next'):
528
"""
529
Decorator requiring user to pass custom test function.
530
531
Args:
532
test_func: Function taking user and returning boolean
533
login_url: Login page URL
534
redirect_field_name: URL parameter for redirect after login
535
536
Returns:
537
Decorator function
538
"""
539
```
540
541
### Session Authentication
542
543
Session constants and utilities for authentication state management.
544
545
```python { .api }
546
SESSION_KEY: str = '_auth_user_id' # Session key for user ID
547
BACKEND_SESSION_KEY: str = '_auth_user_backend' # Session key for auth backend
548
HASH_SESSION_KEY: str = '_auth_user_hash' # Session key for password hash
549
REDIRECT_FIELD_NAME: str = 'next' # Default redirect field name
550
551
def get_user_model() -> Type[AbstractBaseUser]:
552
"""
553
Get the active user model class.
554
555
Returns:
556
User model class from AUTH_USER_MODEL setting
557
"""
558
```
559
560
### Authentication Signals
561
562
Signals for authentication events and user lifecycle.
563
564
```python { .api }
565
user_logged_in: Signal = ...
566
"""
567
Signal sent when user logs in successfully.
568
569
Args:
570
sender: User model class
571
request: HttpRequest object
572
user: User instance that logged in
573
"""
574
575
user_login_failed: Signal = ...
576
"""
577
Signal sent when user login fails.
578
579
Args:
580
sender: None or User model class
581
credentials: Failed login credentials
582
request: HttpRequest object
583
"""
584
585
user_logged_out: Signal = ...
586
"""
587
Signal sent when user logs out.
588
589
Args:
590
sender: User model class
591
request: HttpRequest object
592
user: User instance that logged out
593
"""
594
```
595
596
### Authentication Context Processors
597
598
Context processors adding authentication data to templates.
599
600
```python { .api }
601
def auth(request: HttpRequest) -> dict:
602
"""
603
Add authentication context to templates.
604
605
Args:
606
request: HTTP request object
607
608
Returns:
609
Dictionary with user and perms keys
610
"""
611
```
612
613
### Authentication Middleware
614
615
Middleware for handling user authentication in requests.
616
617
```python { .api }
618
class AuthenticationMiddleware:
619
"""
620
Middleware that adds user attribute to requests.
621
622
Associates user with request based on session authentication.
623
"""
624
def __init__(self, get_response): ...
625
def __call__(self, request: HttpRequest) -> HttpResponse: ...
626
627
class RemoteUserMiddleware:
628
"""
629
Middleware for remote user authentication.
630
631
Authenticates users based on REMOTE_USER header from web server.
632
"""
633
header: str = 'REMOTE_USER'
634
force_logout_if_no_header: bool = True
635
636
def __init__(self, get_response): ...
637
def __call__(self, request: HttpRequest) -> HttpResponse: ...
638
def process_request(self, request: HttpRequest) -> None: ...
639
def clean_username(self, username: str, request: HttpRequest) -> str: ...
640
641
class PersistentRemoteUserMiddleware(RemoteUserMiddleware):
642
"""
643
Remote user middleware that doesn't force logout.
644
645
Allows users to remain logged in without REMOTE_USER header.
646
"""
647
force_logout_if_no_header: bool = False
648
```