Python Django oauth2 request.user返回AnonymousUser

Python Django oauth2 request.user返回AnonymousUser,python,django,oauth-2.0,Python,Django,Oauth 2.0,我是Django新手,正在尝试创建一个API到后端,供iOS客户端使用。目前我正在用curl测试我的API访问 我已使用以下方法成功生成访问令牌: curl -X POST -d "grant_type=password&username=example_user&password=example_password" http://clientID:clientSecret@localhost:8000/o/token/ 产生了以下回应- { "access_token

我是Django新手,正在尝试创建一个API到后端,供iOS客户端使用。目前我正在用curl测试我的API访问

我已使用以下方法成功生成访问令牌:

curl -X POST -d "grant_type=password&username=example_user&password=example_password" http://clientID:clientSecret@localhost:8000/o/token/
产生了以下回应-

{
    "access_token": "oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY", 
    "scope": "write read", 
    "expires_in": 36000, 
    "token_type": "Bearer", 
    "refresh_token": "pxd5rXzz1zZIKEtmqPgE608a4H9E5m"
}
然后,我使用访问令牌尝试访问以下类视图:

from django.http import JsonResponse
from oauth2_provider.views.generic import ProtectedResourceView
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

class post_test(ProtectedResourceView):

    def get(self, request, *args, **kwargs):
        print(request.user)
        return JsonResponse({'Message': "You used a GET request"})

    def post(self, request, *args, **kwargs):
        print(request.user)
        return JsonResponse({'Message': 'You used a POST request'})

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(post_test, self).dispatch(*args, **kwargs)
根据以下请求:

curl -H "Authorization: Bearer oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY" -X GET http://localhost:8000/api/post-test/
通过以下方式正确响应客户:

{"Message": "You used a GET request"}
但是在控制台中,我希望看到
request.user
变量,我得到
AnonymousUser


令牌不是应该分配给
示例用户吗?这不应该是
request.user
返回的吗?

使用
request.resource\u owner
而不是
request.user

Django OAuth工具包区分与承载令牌关联的用户和与可能附加到请求的任何其他Django身份验证关联的用户。具体而言,
ProtectedResourceView
包含来自的行为,其中包括以下分派方法:

def dispatch(self, request, *args, **kwargs):
    # let preflight OPTIONS requests pass
    if request.method.upper() == "OPTIONS":
        return super().dispatch(request, *args, **kwargs)

    # check if the request is valid and the protected resource may be accessed
    valid, r = self.verify_request(request)
    if valid:
        request.resource_owner = r.user
        return super().dispatch(request, *args, **kwargs)
    else:
        return HttpResponseForbidden()

你能解决这个问题吗?不,很遗憾。现在,我正在使用一种变通方法:在POST和GET参数列表中插入用户名。