Django如何在urls.py中为Swagger、Admin等特定URL关闭默认认证
解决方案
1. 关闭Swagger、Admin路径的全局Cognito认证
提供两种可直接落地的方案,按需选择:
方案A:修改自定义认证器添加白名单(改法最少)
直接在你的CognitoAuthentication认证逻辑最开头加路径判断,匹配到Admin、Swagger路径直接跳过认证:
# cheers/utils/authenticator.py from django.conf import settings from rest_framework.authentication import BaseAuthentication class CognitoAuthentication(BaseAuthentication): def authenticate(self, request): # 白名单路径,直接跳过认证 whitelist_paths = ['/admin', '/swagger', '/redoc', '/openapi'] for path in whitelist_paths: if request.path.startswith(path): return None # 原有Cognito认证逻辑保持不变 # ...
方案B:在URL层面对视图覆盖认证配置
如果不想修改认证器,可单独修改urls.py的配置,对指定视图覆盖全局认证类:
Swagger 配置修改
直接对schema_view应用装饰器,清空认证类:
from rest_framework.decorators import authentication_classes, permission_classes schema_view = get_schema_view( openapi.Info( title="Resource API", default_version="v1", description="A sample API for resource with DRF", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="cheersocialinc@gmail.com"), license=openapi.License(name="BSD License"), ), public=True, ) # 覆盖全局认证、权限配置,绕过Cognito认证 schema_view = authentication_classes([])(schema_view) schema_view = permission_classes([permissions.AllowAny])(schema_view)
Admin 配置修改
Django原生Admin默认不会触发DRF的全局认证规则,如果你自定义过Admin视图导致被拦截,可以用装饰器包裹Admin视图:
from django.contrib import admin from django.views.decorators.cache import never_cache # 清空Admin的认证类(仅针对自定义Admin继承了DRF APIView的场景) admin.site.login = authentication_classes([])(admin.site.login) admin.site.index = never_cache(authentication_classes([])(admin.site.index))
2. DEBUG=False时自动禁用Swagger访问
你当前的写法已经实现了该逻辑:SWAGGER_URLS仅在settings.DEBUG为True时才会被加入urlpatterns,DEBUG关闭时Swagger相关路径不会注册,访问会直接返回404。
如果要做双重保险,避免后续误操作把Swagger路径放到全局,可在定义SWAGGER_URLS时加判断:
SWAGGER_URLS = [ path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('openapi.json', schema_view.without_ui(cache_timeout=0), name='schema-json'), ] if settings.DEBUG else []
内容的提问来源于stack exchange,提问作者user12314098
相关产品推荐
相关产品推荐

