DRF认证问题:携带JWT令牌仍提示未提供认证凭证排查
问题排查:JWT授权提示"Authentication credentials were not provided."
核心问题与修复方案
你的代码存在几处关键错误,导致JWT令牌无法被正确识别,进而触发凭证未提供的报错:
1. 视图类覆盖全局认证机制
CreateItemView中显式指定了authentication_classes=[OwnAuthentication],这会替换掉settings里配置的JWTAuthentication。而自定义的OwnAuthentication仅从request.data读取username做认证,完全不处理请求头中的JWT令牌,导致Postman发送的Authorization头无法被解析。
修复:
如果仅需JWT认证,直接移除视图中的authentication_classes配置,继承全局的JWT认证:
# views.py(item_app) class CreateItemView(APIView): serializer_class = CreateItemSerializer # 移除自定义认证类,使用全局的JWTAuthentication # authentication_classes=[OwnAuthentication] permission_classes=[IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] # ... 其余代码
2. 自定义认证类的两处错误
- 模型调用语法错误:
User.object.get应改为User.objects.get(注意复数objects) - 用户模型引用错误:项目配置了自定义用户模型
AUTH_USER_MODEL = "auth_app.Users",但你导入的是Django默认User,需用get_user_model()动态获取当前用户模型
修正后的authentication.py:
from django.contrib.auth import get_user_model from rest_framework import authentication from rest_framework import exceptions User = get_user_model() class OwnAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None)
3. 权限类的拼写与逻辑缺陷
- 类名拼写错误:
IsOnwerOrReadOnly应改为IsOwnerOrReadOnly(修正Owner拼写) - 创建请求权限缺失:
has_object_permission仅处理已有对象的修改/删除权限,对于POST创建请求,需重写has_permission方法确保只有认证用户能发起创建
修正后的permissions.py:
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_permission(self, request, view): # 安全方法直接通过,仅允许认证用户发起POST请求 if request.method in permissions.SAFE_METHODS: return True return request.user.is_authenticated def has_object_permission(self, request, view, obj): # 安全方法直接通过,修改/删除仅允许物品所有者操作 if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user
4. Postman请求头格式验证
确保Postman的Authorization头格式正确:
- 选择
Bearer Token类型,粘贴获取到的access token - 或手动设置请求头:
Authorization: Bearer <你的access_token>
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

