【问题标题】:How to get access token in apiview如何在 apiview 中获取访问令牌
【发布时间】:2019-08-12 12:04:57
【问题描述】:

我想在我的APIView 中获取访问令牌。我正在使用Oauth2client_credentials。甚至将self.request.authself.request.user 打印为None。我想要在 djnago restframework 中创建 client_credentials 应用程序的用户。

# Employee API
class EmployeeListAPIView(generics.ListAPIView):
    serializer_class = UserSerializer
    # permission_classes = [UserIsAuthenticated]

    def get_queryset(self, *args, **kwargs):
        print('request.user', self.request.auth)
        print('request.user', self.request.user)
        print('Access Token', self.access_token)

        qs = User.objects.exclude(
                Q(userprofile__user_is_deleted = True)|
                Q(userprofile__user_company__company_is_deleted=True)
            ).filter(
                Q(userprofile__user_company =self.request.auth.application.company) &
                Q(userprofile__user_role__id=4)
            )
        return qs

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    如果您想要访问令牌,您可以通过request.META.get('HTTP_AUTHORIZATION') 获得。

    如果你想要用户或客户端,那么你可以

    from django-oauth2-provider.provider.oauth2.models import AccessToken
    
    accesstoken=AccessToken.objects.get(token=request.META.get('HTTP_AUTHORIZATION'))
    user=accesstoken.user
    client=accesstoken.client
    

    【讨论】:

      【解决方案2】:

      还不能离开 cmets,所以我需要留下答案 :) 您确定您的中间件设置正确吗?

      这是一个例子,也许它会有所帮助。 How can I get the current logged in user from a django-oauth-toolkit token?

      这实际上很奇怪,你无法通过 self.request.user 获取用户。它应该还给他。

      尝试打印您正在查看的请求对象,看看里面有什么,也许会有所帮助。

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 2012-02-15
        • 1970-01-01
        • 2019-09-09
        • 2022-10-13
        • 2018-10-11
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多