You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于dj_rest_auth.jwt_auth.JWTCookieAuthentication的报错求助

解决drf-spectacular无法识别JWTCookieAuthentication的报错

这个报错的核心原因是drf-spectacular默认没有为dj_rest_auth.jwt_auth.JWTCookieAuthentication注册对应的OpenAPI认证扩展,需要自定义扩展类让它识别该认证方式。

解决步骤:

  1. 在你的Django项目中创建一个扩展文件(比如your_app/schema_extensions.py,替换your_app为实际的app名称),写入以下代码:
from drf_spectacular.extensions import OpenApiAuthenticationExtension
from dj_rest_auth.jwt_auth import JWTCookieAuthentication

class JWTCookieAuthenticationExtension(OpenApiAuthenticationExtension):
    target_class = 'dj_rest_auth.jwt_auth.JWTCookieAuthentication'
    name = 'JWTCookieAuthentication'

    def get_security_definition(self, auto_schema):
        return {
            'type': 'apiKey',
            'in': 'cookie',
            'name': JWTCookieAuthentication.jwt_cookie_name,
            'description': '通过JWT Cookie完成身份验证'
        }
  1. 在项目的settings.py中配置drf-spectacular,添加这个扩展。如果没有SPECTACULAR_SETTINGS配置项,就新建一个:
SPECTACULAR_SETTINGS = {
    # 可根据需求添加其他配置,比如标题、版本等
    'TITLE': '你的API文档标题',
    'VERSION': '1.0.0',
    'EXTENSIONS': [
        'your_app.schema_extensions.JWTCookieAuthenticationExtension',  # 替换为实际路径
    ],
}
  1. 重启Django服务器,终端的报错信息就会消失,同时API文档也会正确识别JWTCookieAuthentication认证方式。

内容的提问来源于stack exchange,提问作者Developer Maleek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:54:21