如何在djangorestframework-simplejwt中使用JWTTokenUserAuthentication实验特性及微服务SSO认证
Hey there, let's break down your two questions with practical, actionable steps:
First off, JWTTokenUserAuthentication is an experimental feature built to bypass Django's database user queries entirely—instead, it pulls user identity directly from the JWT payload. This is perfect for microservices where you don't want every service tied to your core user database. Here's how to set it up:
Update to a compatible version: Make sure you're running a recent enough release of
djangorestframework-simplejwt(this feature was added in v5.0+, so upgrade if needed):pip install --upgrade djangorestframework-simplejwtAdd it to your authentication classes: In your project's
settings.py, include the backend in DRF's default authentication classes. You can keep the standardJWTAuthenticationalongside it if you need both behaviors:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', ], }Ensure your JWT payload has required user data: Since this backend doesn't query the database, your token's payload must include all user fields your services need (like
user_idorusername). Customize the payload handler insettings.py:def custom_token_payload(token): payload = token.get_payload() # Add user fields to the payload payload['user_id'] = token.user.id payload['username'] = token.user.username return payload SIMPLE_JWT = { 'TOKEN_PAYLOAD_HANDLER': 'your_project_name.settings.custom_token_payload', # Keep your other JWT configs here (expiry time, etc.) }Important caveats:
- It's experimental, so test thoroughly before production use.
- Since it skips database checks, it won't validate if a user has been disabled or deleted. If you need these checks, stick with
JWTAuthenticationor add custom middleware. - Use a secure asymmetric algorithm like RS256 to prevent token forgery if your services are distributed.
For microservices SSO using simplejwt, the goal is to have your auth service issue JWT tokens that all other Django services trust. Here's how to pull it off:
Core Idea
Your standalone auth service handles login/logout and token issuance/refresh. All other business services only validate the token's signature and extract user data—no local login logic needed.
Step 1: Configure the Auth Service
- Make sure your auth service is set up with simplejwt, and exposes endpoints like
TokenObtainPairView(for login) andTokenRefreshView(for token renewal). - Use asymmetric encryption (RS256) for token signing (way more secure than HS256 for distributed services):
- Generate an RSA key pair (keep the private key safe on your auth service only):
openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -pubout -out public.pem - Configure your auth service's
settings.py:from datetime import timedelta SIMPLE_JWT = { 'ALGORITHM': 'RS256', 'SIGNING_KEY': open('path/to/private.pem').read(), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), }
- Generate an RSA key pair (keep the private key safe on your auth service only):
Step 2: Configure All Business Services
Yes, you do need to update DEFAULT_AUTHENTICATION_CLASSES in every Django project—this tells DRF to accept and validate JWT tokens. Here's what to do:
Add the JWT auth class: In each business service's
settings.py:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ # Use JWTTokenUserAuthentication if you want to skip DB queries, # or JWTAuthentication if you need to fetch user data from a local DB/cache 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], }Configure token validation: Use the public key from your auth service to verify token signatures:
SIMPLE_JWT = { 'ALGORITHM': 'RS256', 'VERIFYING_KEY': open('path/to/public.pem').read(), # Disable refresh token rotation if your business services don't handle it 'ROTATE_REFRESH_TOKENS': False, }
Key Tips for Smooth SSO
- Secure key management: Never share the private key with any other service. Distribute the public key safely (e.g., via config management tools).
- User data sync (optional): If business services need more user data than what's in the JWT payload, either extend the payload or sync user data periodically from the auth service to a local cache.
- CORS setup: Ensure all services allow cross-origin requests from your frontend, so tokens can be sent between domains.
- Error handling: Teach your frontend to handle 401 responses by redirecting users to the auth service for token refresh or re-login.
内容的提问来源于stack exchange,提问作者Abishek

