如何在Django REST Framework中实现用户认证与接口权限控制?
Hey there! Let's walk through how to set up user authentication and control access to your POST/PUT/DELETE endpoints in Django REST Framework. I'll break this down into clear, actionable steps:
Django REST Framework (DRF) comes with several built-in authentication methods. Let's start with Token Authentication—it's simple, stateless, and perfect for API scenarios.
Step 1: Configure DRF in settings.py
First, enable the token authentication app and set it as your default authentication class:
# settings.py INSTALLED_APPS = [ # Your existing apps 'rest_framework', 'rest_framework.authtoken', # Add this for token support ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # Optional: Add SessionAuthentication if you want to use the DRF browsable API with login 'rest_framework.authentication.SessionAuthentication', ], }
Step 2: Add a Token Generation Endpoint
Let users obtain an authentication token by sending their username and password. Add this to your project's urls.py:
# urls.py from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ # Your existing URLs path('api/token/', obtain_auth_token, name='api_token_auth'), ]
Now users can send a POST request to /api/token/ with username and password in the body to get their token. They'll include this token in subsequent requests via the Authorization header:Authorization: Token <their-generated-token>
Next, we'll restrict access to your POST/PUT/DELETE endpoints so only authorized users can use them. DRF has built-in permission classes, and you can also create custom ones for specific needs.
Option 1: Use Built-in Permissions
If you want to limit write operations (POST/PUT/DELETE) to admin users only, while allowing authenticated users to read (GET), you can set per-view permissions:
from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response class YourDataView(APIView): # Apply token authentication to all requests authentication_classes = [TokenAuthentication] def get_permissions(self): # Set permissions based on the request method if self.request.method in ['POST', 'PUT', 'DELETE']: # Only admins can perform write operations return [IsAdminUser()] # All authenticated users can read return [IsAuthenticated()] def get(self, request): # Your GET logic here return Response({"data": "Your read-only data"}) def post(self, request): # Your POST logic here return Response({"message": "Data created successfully"}) def put(self, request): # Your PUT logic here return Response({"message": "Data updated successfully"}) def delete(self, request): # Your DELETE logic here return Response({"message": "Data deleted successfully"})
Option 2: Create a Custom Permission
If you need more granular control (e.g., allowing specific user groups or individual users), create a custom permission class:
from rest_framework.permissions import BasePermission class CanModifyData(BasePermission): """Custom permission to only allow specific users/groups to modify data""" def has_permission(self, request, view): # Allow access if user is in the "DataEditors" group OR has a specific user ID return ( request.user.groups.filter(name="DataEditors").exists() or request.user.id in [1, 4, 7] # Replace with your allowed user IDs )
Then use it in your view:
class YourDataView(APIView): authentication_classes = [TokenAuthentication] def get_permissions(self): if self.request.method in ['POST', 'PUT', 'DELETE']: # Require authentication AND custom permission for writes return [IsAuthenticated(), CanModifyData()] return [IsAuthenticated()] # ... rest of your view methods ...
Option 3: Global Default Permissions
If you want all endpoints to require authentication by default, set this in settings.py:
REST_FRAMEWORK = { # ... your authentication classes ... 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] }
You can still override this in individual views if needed.
- Use tools like Postman or curl to send a POST request to
/api/token/with valid credentials to get a token. - For write operations (POST/PUT/DELETE), include the token in the
Authorizationheader. If the user isn't authorized, DRF will return a403 Forbiddenresponse.
内容的提问来源于stack exchange,提问作者Mahdi Sorkhmiri




