1. Ideas for implementing Token authentication
Generate a token after the user logs in: After the user logs in successfully, the server generates a token and returns it to the client.
The client carries the token when requesting: the client puts the token in the HTTP request headers every time it requests.
Server-side verification Token: Django backend parses the token in the request and verify its legitimacy.
The token verification passes, allowing access to the interface; otherwise, an unauthorized error message is returned.
2. Environmental preparation
In the Django project, we can use rest_framework.authtoken or customize the token authentication logic. Here are two ways:
- Token authentication based on Django REST framework (DRF)
- Custom Token Certification
3. Token authentication based on Django REST Framework (DRF)
Django REST Framework provides an off-the-shelf Token authentication mechanism, and the following are the implementation steps.
1. Install Django REST framework
If the Django REST framework is not installed yet, use pip to install:
pip install djangorestframework pip install
2. Add to Django Configuration
existEnable Django REST framework and Token authentication:
INSTALLED_APPS = [ '', '', '', '', '', '', 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.', ), }
3. Generate a Token table
Run the Django migration command to create the data tables required for Token authentication:
python migrate
4. Create API View
Create a user login interface, generate and return a token.
from import authenticate from rest_framework. import Token from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status class LoginView(APIView): def post(self, request): username = ("username") password = ("password") user = authenticate(username=username, password=password) if user: token, created = .get_or_create(user=user) return Response({"token": }) return Response({"error": "Invalid Credentials"}, status=status.HTTP_401_UNAUTHORIZED)
5. Protect API endpoints
Use in API viewTokenAuthentication
Protect API, only users holding valid tokens are allowed to access:
from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response class ProtectedView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self, request): return Response({"message": "You have access to this protected endpoint."})
6. Test API
Get Token:
curl -X POST http://127.0.0.1:8000/api/login/ -H "Content-Type: application/json" -d '{"username": "admin", "password": "password"}'
The server returns:
{"token": "abc123xyz456"}
Accessing protected APIs:
curl -X GET http://127.0.0.1:8000/api/protected/ -H "Authorization: Token abc123xyz456"
The server returns:
{"message": "You have access to this protected endpoint."}
4. Customize the Token certification plan
If you do not use the DRF's ownTokenAuthentication
, we can also customize Token authentication.
1. Customize the Token model
existCreate a token storage table in:
from import models from import User import uuid class CustomToken(): user = (User, on_delete=) key = (max_length=255, unique=True, default=uuid.uuid4) created_at = (auto_now_add=True) def __str__(self): return
2. Create token generation logic
Define the login logic in , and generate a custom token:
from import authenticate from import JsonResponse from .models import CustomToken def custom_login(request): if == "POST": username = ("username") password = ("password") user = authenticate(username=username, password=password) if user: token, created = .get_or_create(user=user) return JsonResponse({"token": }) return JsonResponse({"error": "Invalid credentials"}, status=401)
3. Middleware intercept Token
Define the Token verification logic in :
from import JsonResponse from .models import CustomToken class TokenMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): token = ("Authorization") if not token: return JsonResponse({"error": "Token missing"}, status=401) try: user_token = (key=token) = user_token.user except : return JsonResponse({"error": "Invalid token"}, status=401) return self.get_response(request)
Then, inEnable middleware:
MIDDLEWARE = [ '', '', '', '', '', '', '', '', # Add custom Token authentication middleware]
4. Protected API
Define the interface that requires Token authentication in
from import JsonResponse def protected_view(request): return JsonResponse({"message": "Welcome, you are authenticated!"})
5. Test
Get Token:
curl -X POST http://127.0.0.1:8000/custom_login/ -d "username=admin&password=admin"
return:
{"token": "abc123xyz456"}
Accessing protected API:
curl -X GET http://127.0.0.1:8000/protected_view/ -H "Authorization: abc123xyz456"
return:
{"message": "Welcome, you are authenticated!"}
5. Summary
This plan introduces two methods to implement interface Token authentication in Django:
Token authentication using Django REST framework (DRF): Applicable to REST API, easy to use.
Custom Token Certification: Applicable to more flexible needs, customize token rules, expiration policies, etc.
The above code and steps ensure the security of the API, avoid unauthorized access, and are suitable for user authentication for Django Web projects.
This is the article about the detailed explanation of the method of implementing interface token detection in Django. For more related Django interface token detection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!