我是一名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请求:
curl -H "Authorization: Bearer oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY" -X GET http://localhost:8000/api/post-test/
以下是适当的响应客户端的方式:
{"Message": "You used a GET request"}
但是在控制台中,我期望看到request.user
变量,但实际上我看到的是AnonymousUser
。
这个令牌不应该分配给example_user
吗?request.user
不应该返回这个吗?