You need to enable JavaScript to run this app. Django REST Framework JWT认证:提供有效令牌仍提示未提供认证凭证
优惠活动
大模型
产品
解决方案
定价
更多

Django REST Framework JWT认证:提供有效令牌仍提示未提供认证凭证

DRF携带有效JWT令牌仍提示「未提供认证凭证」的解决方案

问题直接根因

视图层的authentication_classes配置优先级远高于全局settings里的默认认证配置,一旦在视图里重写这个属性,全局默认的JWTAuthentication就会被完全覆盖,不会再生效。

你当前的op_ViewSet重写后的认证列表为[TokenAuthentication, SessionAuthentication, BasicAuthentication],这三个认证类的解析逻辑没有一个支持SimpleJWT生成的Bearer格式令牌:

  • TokenAuthentication:仅能解析DRF自带数据库存储的普通永久令牌,无法识别JWT结构的令牌
  • SessionAuthentication:仅能校验浏览器请求携带的会话Cookie,不读取Authorization请求头
  • BasicAuthentication:仅能解析Base64编码的账号密码凭证,不识别Bearer格式的JWT

当所有认证类都无法从请求中提取到合法凭证时,DRF就会抛出如下错误:

{
    "detail": "Authentication credentials were not provided."
}

落地修复操作

  1. 修正视图的认证类配置
    两种可选写法,选其一即可:
    • 直接删掉视图里重写的authentication_classes属性,让视图自动继承全局settings中配置的JWTAuthentication
    • 手动把JWTAuthentication加入到视图的认证列表中,示例代码:
      from rest_framework_simplejwt.authentication import JWTAuthentication
      from rest_framework.authentication import SessionAuthentication, BasicAuthentication
      from rest_framework import permissions, viewsets
      
      class op_ViewSet(viewsets.ViewSet):
          permission_classes = (permissions.IsAuthenticated,)
          # 把JWTAuthentication纳入支持的认证类型列表
          authentication_classes = [JWTAuthentication, SessionAuthentication, BasicAuthentication]
      
  2. 补全校验容易遗漏的细节
    • 确认Swagger UI中传入的Authorization头格式合规,必须为Bearer <access令牌字符串>,不能只粘贴裸令牌缺失Bearer前缀
    • 确认请求携带的access令牌未过期(你配置的access有效期仅3分钟,超时后需要调用refresh接口获取新的有效令牌)

内容的提问来源于stack exchange,提问作者Talib Daryabi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 21:54:07