大型Django单体项目拆微服务后Django admin与认证授权疑问
Hey there! These are two really key questions when moving a Django monolith to microservices—since Django Admin and auth are such integral parts of how you work, it makes total sense to want to keep using them smoothly. Let’s dive into each one:
1. Using Django Admin Across Microservices
Absolutely, you can keep using Django Admin to manage data across all your microservices—you just need to adjust how it connects to each service’s data. Here are the most practical approaches for a smooth experience:
Centralized Admin Service (best for unified UI):
Build a dedicated, lightweight Django service whose sole job is hosting the Admin interface. This service doesn’t have its own business database; instead, it acts as a proxy to your other microservices via their APIs.- Create proxy models in this Admin service (set
managed = Falsein the model’s Meta class so Django doesn’t try to create database tables). - Override core
ModelAdminmethods likeget_queryset,save_model, anddelete_modelto make HTTP calls to the corresponding microservice’s API instead of hitting a local database.
Example snippet for a remote user model:
from django.db import models from django.contrib import admin import requests class RemoteUser(models.Model): id = models.IntegerField(primary_key=True) username = models.CharField(max_length=150) email = models.EmailField() class Meta: managed = False verbose_name = "User" class RemoteUserAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'email') def get_queryset(self, request): # Fetch data from user microservice API response = requests.get('http://user-service/api/users/') users = response.json() return [RemoteUser(**user) for user in users] def save_model(self, request, obj, form, change): if change: requests.put(f'http://user-service/api/users/{obj.id}/', data=form.cleaned_data) else: requests.post('http://user-service/api/users/', data=form.cleaned_data) admin.site.register(RemoteUser, RemoteUserAdmin)To make this smoother: add caching for frequent API calls, handle service downtime with friendly error messages, and use async tasks for bulk operations to avoid UI timeouts.
- Create proxy models in this Admin service (set
Federated Admin Instances (less ideal for unified access):
Each microservice can keep its own Django Admin, but this forces your team to log into multiple interfaces. You can improve this by integrating with a shared auth service (more on that below) to sync login sessions, but it’s still less seamless than a centralized admin.
2. Django Auth in Microservices (Extracting to a Standalone Service)
Yes, you can absolutely keep using Django’s built-in auth features—and extracting them into a dedicated auth service is the recommended approach for microservices. Here’s how to pull it off:
Build a standalone Auth Service:
Migrate Django’s core auth layer (User model, permissions, groups) into its own microservice. Use Django REST Framework (DRF) to wrap these features into APIs, so other services can interact with it.- Use packages like
django-rest-framework-simplejwtto handle token-based authentication (JWT is ideal for microservices since it’s stateless). - Expose endpoints for: token generation/verification, user registration, fetching user details, and checking permissions.
Example auth service URLs:
from django.urls import path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) from .views import UserDetailView, PermissionCheckView urlpatterns = [ path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/users/<int:pk>/', UserDetailView.as_view(), name='user_detail'), path('api/permissions/check/', PermissionCheckView.as_view(), name='permission_check'), ]- Use packages like
Integrate Auth with Other Services:
- Client-to-service requests: Clients first log into the auth service to get a JWT, then include this token in the
Authorization: Bearer <token>header for all requests to other microservices. - Service-to-service communication: Each microservice validates incoming tokens by calling the auth service’s
/api/token/verifyendpoint. For internal calls, you can also use dedicated service accounts with their own tokens.
Example middleware for a microservice to validate tokens:
import requests from django.http import JsonResponse class AuthValidationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): auth_header = request.headers.get('Authorization') if not auth_header or not auth_header.startswith('Bearer '): return JsonResponse({'error': 'Unauthorized'}, status=401) token = auth_header.split(' ')[1] verify_response = requests.post( 'http://auth-service/api/token/verify/', json={'token': token} ) if verify_response.status_code != 200: return JsonResponse({'error': 'Invalid token'}, status=401) # Attach user data to the request for downstream use user_id = verify_response.json()['user_id'] user_response = requests.get(f'http://auth-service/api/users/{user_id}/') request.user = user_response.json() response = self.get_response(request) return response- Client-to-service requests: Clients first log into the auth service to get a JWT, then include this token in the
Pro Tips for Smooth Operation:
- Make the auth service highly available (use load balancing and multiple instances) since every service depends on it.
- Cache user details and permissions in other services to reduce repeated calls to the auth service.
- Implement fallback logic for auth service outages (e.g., allow read-only access for critical endpoints if auth is down).
内容的提问来源于stack exchange,提问作者mrgoos

