Middle
207
How does the authentication system work in Django?
Answer from AI
sobes.tech AI
In Django, authentication is based on an pluggable backend that handles users, groups, and permissions.
Main components:
- Users: The
django.contrib.auth.models.Usermodel stores user information (name, hashed password, email, etc.). - Groups: The
django.contrib.auth.models.Groupmodel groups users for easier permission management. - Permissions: The
django.contrib.auth.models.Permissionmodel defines what actions a user is allowed to perform (view, add, change, delete models). - Authentication Backends: Classes that implement methods for authentication (
authenticate) and authorization (get_user,has_perm,has_module_perms). By default,django.contrib.auth.backends.ModelBackendis used.
Authentication process:
- The user submits login and password (usually via a form).
- Django calls the
authenticate()method of configured backends, passing the credentials. - The backend searches for the user by login.
- If the user is found, the backend checks the password (comparing hashes).
- If the check is successful,
authenticate()returns the user object. - Django calls
login()(in the view or middleware), which sets the session for the user.
Example usage in a view:
# views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('some_success_page')
else:
# Handle authentication error
pass
return render(request, 'login.html')
Main functions and decorators for authentication and permission checks:
@login_required: Decorator for views that require user authentication.@permission_required('app_label.permission_code'): Decorator for views that require a specific permission.user.is_authenticated: Checks if the user is authenticated.user.has_perm('app_label.permission_code'): Checks if the user has a specific permission.user.has_module_perms('app_label'): Checks if the user has permissions for a model in a specific app.
Configuration:
AUTHENTICATION_BACKENDS: List of registered backends. Defaults to['django.contrib.auth.backends.ModelBackend'].LOGIN_URL: URL to redirect unauthenticated users when using@login_required.LOGIN_REDIRECT_URL: URL to redirect after successful login.