Django Rest Swagger 2.2.0中TokenAuthentication API显示及授权问题求助
Hey there, let's break down solutions for your two core issues with DRF 3.7.7 and django-rest-swagger (both 2.1.2 and 2.2.0):
1. Correct Configuration for APIView with TokenAuthentication
First, let's fix the auth setup and Swagger doc visibility for your authenticated views:
a. Local vs Global Auth Setup
Your current approach of setting authentication_classes and permission_classes directly on RandomClass is totally valid for per-view authentication. If you wanted to apply token auth to all views by default, you could add this to your settings.py:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] }
Stick with your local setup if you only need auth on specific views.
b. Let Unauthenticated Users Browse Docs (Without Accessing the API)
Your current problem is that users need to auth first to even see the docs for IsAuthenticated views. To fix this, create a custom schema class that skips permission checks during schema generation:
from rest_framework.schemas import AutoSchema class DocAutoSchema(AutoSchema): def get_permissions(self, path, method): # Bypass permissions so docs are visible to everyone return [] # Update your view to use this schema: class RandomClass(APIView): authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated, ) schema = DocAutoSchema( manual_fields=[ coreapi.Field( "page_id", required=True, location="query", type="string", description="Facebook Page ID" ) ] )
Now anyone can view the docs, but actual API calls will still enforce IsAuthenticated.
c. Link Swagger's Auth Flow to Your Token Setup
Your existing SECURITY_DEFINITIONS in settings.py is correct. To make sure Swagger prompts users to auth for this view, add the security attribute to your schema:
schema = DocAutoSchema( manual_fields=[...], security=[{'api_key': []}] # Tells Swagger this view requires your api_key auth )
This will show the "Authorize" button in Swagger, letting users input their token into the Authorization header.
2. Fixing JSON Submission & Auth Compatibility in django-rest-swagger 2.2.0
Upgrading to 2.2.0 can break JSON submission and schema handling for multi-method views. Here's how to fix it:
a. Enable JSON Editor & Adjust Swagger Settings
First, update your SWAGGER_SETTINGS to support raw JSON input:
SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, 'JSON_EDITOR': True, # Lets users input raw JSON directly 'SHOW_REQUEST_HEADERS': True, # Helps verify the Authorization header is sent 'DOC_EXPANSION': None, 'APIS_SORTER': None, 'OPERATIONS_SORTER': None, 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', 'put', 'delete', 'patch' ], 'VALIDATOR_URL': '', }
b. Fix Duplicate Schemas for Multi-Method Views
To generate unique schemas for each HTTP method (like GET vs POST), override the get_schema method in your view:
class RandomClass(APIView): authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated, ) def get_schema(self, request=None, **kwargs): if request and request.method == 'GET': return DocAutoSchema(manual_fields=[ coreapi.Field( "page_id", required=True, location="query", type="string", description="Facebook Page ID" ) ]) elif request and request.method == 'POST': return DocAutoSchema(manual_fields=[ coreapi.Field( "payload", required=True, location="body", type="string", description="Raw JSON request body" ) ]) return super().get_schema(request, **kwargs) def get(self, request): # Your GET logic here pass def post(self, request): # Your POST logic here pass
This ensures each method gets its own custom schema in Swagger.
c. Workaround for Auth & JSON Submission Conflict
If you're still having trouble submitting JSON after auth, make sure to:
- Manually set the
Content-Typeheader toapplication/jsonin Swagger's request editor - Explicitly define the body field in your schema with
location="body"(as shown above) - Clear your browser cache sometimes—swagger can cache old schema definitions
内容的提问来源于stack exchange,提问作者Mehran

