【问题标题】:How do I pass a django auth token to view or serializer?如何将 django 身份验证令牌传递给查看或序列化程序?
【发布时间】:2022-01-20 00:10:45
【问题描述】:

我正在尝试使用“rest_framework.authentication.TokenAuthentication”提供的令牌,

我想使用视图或序列化程序中的令牌。我使用什么方法使令牌在我的应用程序中可见?这是我尝试过的,只有当前用户返回。 'auth' 键不返回任何值。

查看

   class ReadProductView(generics.ListAPIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
                'auth': str(request.auth),
                'user': str(request.user),
        }
        return Response(content)

设置...


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',  #Token authentication

    ],
}

【问题讨论】:

  • 您能分享整个视图和您的 DRF 设置吗?
  • 现在包括我的设置。

标签: python django django-rest-framework


【解决方案1】:

我想通了。我需要在视图中添加一个库才能访问令牌。

图书馆:

从 rest_framework.authtoken.models 导入令牌

然后我在基于类的视图中使用 get 方法获取了令牌。


    def get(self, request, format=None):
        content = {
                'auth': str(Token.objects.get()),
                'user': str(request.user),
        }
        return Response(content)

【讨论】:

  • 如果您拥有多个令牌,这将不起作用,并且仅使用get 并不能保证您获得的令牌是针对当前用户的。没有拿到token的原因很可能是认证用户取自SessionAuthentication
猜你喜欢
  • 2021-04-13
  • 2015-02-24
  • 2019-06-16
  • 2016-10-01
  • 2021-08-17
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多