为何drf-spectacular的Swagger界面中不显示Authorize按钮?
自定义认证类缺少OpenAPI规范支持
drf-simplejwt的JWTAuthentication内置了适配OpenAPI的认证方案定义,而自定义的CustomAuthentication需要明确提供对应的OpenAPI安全方案配置。如果没有通过@extend_schema_auth装饰器或手动定义security scheme,drf-spectacular无法识别该认证类型,swagger-ui就不会生成Authorize按钮。自定义认证类结构不符合识别要求
确保自定义类正确继承自rest_framework.authentication.BaseAuthentication,并且类中存在符合DRF规范的authenticate方法。drf-spectacular依赖DRF的认证类结构来识别可支持的认证方式,结构不规范会导致无法被扫描到。SERVE_AUTHENTICATION中的类路径错误
检查配置里的custom.custom_authentication.CustomAuthentication路径是否完全正确:确认customapp已添加到INSTALLED_APPS,模块文件存在且类名拼写无误。路径错误会导致drf-spectacular无法加载该认证类,自然不会显示对应的授权入口。未注册认证方案到spectacular组件
即使类路径正确,也需要在spectacular中明确注册该认证对应的组件。可以在自定义认证类上添加装饰器:from drf_spectacular.utils import extend_schema_auth @extend_schema_auth( {"type": "apiKey", "in": "header", "name": "Authorization"} ) class CustomAuthentication(BaseAuthentication): # 你的认证逻辑或者在
SPECTACULAR_SETTINGS中配置COMPONENTS来手动添加security scheme。drf-spectacular版本兼容性问题
部分旧版本的drf-spectacular对自定义认证的支持有限,尝试升级到最新稳定版本,可能解决识别自定义认证类的问题。
内容的提问来源于stack exchange,提问作者nope_that_does_not_work

