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

Django Rest-Framework搭配simpleJWT时Postman请求返回Anonymous User问题

问题根因

你遇到的浏览器能正常返回、Postman返回匿名用户的核心原因是:

  • 浏览器侧已经登录过Django后台,默认走SessionAuthentication会话认证,所以能正常识别用户身份
  • 你的接口没有开启SimpleJWT的JWTAuthentication认证类,Postman携带的JWT请求头没有被后端解析处理,所以识别为匿名用户
    还有可能伴随Postman请求头配置错误的次要原因。
解决步骤
    1. 配置DRF认证规则(二选一即可)
      方案A:全局配置(所有接口默认启用JWT和Session认证)
      在settings.py中添加以下配置:
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_simplejwt.authentication.JWTAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ),
        # 可选配置:默认所有接口需要登录才能访问
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        )
    }
    
    方案B:单独给目标接口配置认证类
    修改你的接口代码,添加认证和权限装饰器:
    from rest_framework.decorators import api_view, authentication_classes, permission_classes
    from rest_framework_simplejwt.authentication import JWTAuthentication
    from rest_framework.permissions import IsAuthenticated
    
    @api_view(['GET'])
    @authentication_classes([JWTAuthentication, SessionAuthentication])
    @permission_classes([IsAuthenticated])
    def get_user_profile(request):
        print(request.user)
        user = request.user
        serializer = UserSerializer(user, many=False)
        return Response(serializer.data)
    
    1. 校验Postman配置
    • 确认你填入的是未过期的Access Token,不要误用Refresh Token
    • 确认Authorization请求头的值格式正确:Bearer 和Token之间必须有且仅有1个空格,例如Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
    • 确认请求方法为GET,和接口声明的允许方法一致
    1. 额外排查(如果以上操作后仍有问题)
      在视图中打印请求头print(request.META.get('HTTP_AUTHORIZATION')),确认Postman发送的Authorization头有没有被Nginx等反向代理中间件拦截丢弃,如果被丢弃需要修改反向代理配置允许传递Authorization头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:00