【问题标题】:DRF: request.user returns nothing for token based authenticationDRF:request.user 对基于令牌的身份验证不返回任何内容
【发布时间】:2021-09-05 18:45:37
【问题描述】:

我基本上是 DRF 的新手,并试图通过移动应用程序创建一个 API 端点来更新用户,这是我的代码,

class MobileAppUserUpdateView(APIView):
    
    def post(self, request, format=None):
        user = request.user

        print('USER',user) #<- prints nothing
        print('TOKEN',request.auth) #<- prints the token
        
        return ResponseBuilder.success([constants.RECORD_UPDATED])

我想访问使用身份验证令牌发出该请求但在那里一无所获的用户。这是我的 DRF 设置,

NON_FIELD_ERRORS_KEY = 'message'

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        # 'rest_framework.authentication.TokenAuthentication',
        
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.BasicAuthentication',
       'rest_framework.authentication.TokenAuthentication',
   ),
   'NON_FIELD_ERRORS_KEY': NON_FIELD_ERRORS_KEY,
   
}

我还根据文档在INSTALLED_APPS 列表中添加了"rest_framework.authtoken"。任何帮助将不胜感激...

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    问题出在用户表中,用户模型为 str 方法返回电子邮件,而电子邮件字段的值为空,这就是为什么我尝试打印它时什么也没得到。

    【讨论】:

      【解决方案2】:

      还有几件事..

      您需要在包含TokenAuthenticationMobileAppUserUpdateView中添加authentication_classes,如下所示:

      class MobileAppUserUpdateView(APIView):
          authentication_classes = [TokenAuthentication]
          permission_classes = [IsAuthenticated]
      
          def post(self, request, format=None):
              ...
      

      然后确保您在INSTALLED_APPS 设置中添加了rest_framework.authtoken

      INSTALLED_APPS = [
          ...
          'rest_framework.authtoken'
      ]
      

      然后在更改设置后运行manage.py migrate

      使用调试器调试代码并检查您的 request 对象正在接收什么。

      您可以关注此doc 了解更多信息。

      【讨论】:

      • Sharme,我尝试添加这些类,但仍然是同样的问题。如果我已经在默认设置中添加了这些类,为什么还要添加这些类?
      • 这只是设置身份验证方案的另一种方式。
      • 我想通了,request.auth 返回的是空字符串,因为在模型中我指定返回电子邮件但电子邮件在数据库中的值为空。
      • @RopAliMunshi 请回答您自己的问题并将其标记为已解决。
      猜你喜欢
      • 2021-01-25
      • 1970-01-01
      • 2016-01-23
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2017-07-10
      相关资源
      最近更新 更多