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

Django REST Framework中Simple JWT POST请求401未授权问题求助

解决POST请求401 Unauthorized问题

1. 确认请求是否正确携带认证头

所有需要认证的POST请求,必须在请求头中包含Authorization: Bearer <你的access_token>,注意:

  • Bearer后面必须有一个空格
  • 确保access_token未过期(你的配置里access_token有效期为5分钟)
  • 前端发送POST请求时,不要遗漏这个请求头,避免拼写错误(比如写成auth或Authorization大小写错误)

2. 针对匿名可访问的接口(比如评论提交)

如果你的评论接口允许未登录用户提交,需要给视图单独设置权限类,覆盖全局的IsAuthenticated:

from rest_framework import permissions

class PostCommentApiView(APIView):
    # 添加这行,允许匿名访问
    permission_classes = (permissions.AllowAny,)
    
    @swagger_auto_schema(
        request_body=openapi.Schema(
          type=openapi.TYPE_OBJECT,
          properties={
              'post_id': openapi.Schema(type=openapi.TYPE_INTEGER),
              'name': openapi.Schema(type=openapi.TYPE_STRING),
              'email': openapi.Schema(type=openapi.TYPE_STRING),
              'comment': openapi.Schema(type=openapi.TYPE_STRING),
          },
        ),
    )
    def post(self, request):
        # 原代码保持不变
        post_id = request.data["post_id"]
        name = request.data["name"]
        email = request.data["email"]
        comment = request.data["comment"]

        post = api_models.Post.objects.get(id=post_id)

        api_models.Comment.objects.create(
          post=post,
          name=name,
          email=email,
          comment=comment,
        )

        api_models.Notification.objects.create(
            user=post.user,
            post=post,
            type="Comment"
          )
        
        return Response({"message": "Comment Sent"}, status=status.HTTP_201_CREATED)

3. Swagger测试时的认证设置

如果用Swagger测试接口,先通过登录接口获取access_token,然后点击Swagger页面右上角的Authorize按钮,输入Bearer <你的access_token>(例如Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...),点击Authorize后,后续所有请求会自动携带认证头。

4. 排查全局配置问题

确认你的REST_FRAMEWORK配置中,认证类和权限类的顺序与设置正确:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

该配置是正确的,全局要求所有接口必须登录才能访问,因此需要认证的POST请求必须携带token,无需认证的接口则单独设置权限类。

额外优化建议

  • 避免直接在request.data中取值,建议用request.data.get("key", None)并做参数校验,防止缺少参数抛出KeyError
  • 处理api_models.Post.objects.get(id=post_id)可能出现的Post.DoesNotExist异常,改用get_object_or_404返回404错误:
from django.shortcuts import get_object_or_404

post = get_object_or_404(api_models.Post, id=post_id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:44:55