python - Django oauth2 request.user 返回 AnonymousUser

标签 python django oauth-2.0

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

我已经使用以下方法成功生成了访问 token :

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"
}

然后我使用访问 token 尝试访问以下类 View :

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

token 不是应该分配给 example_user 吗?这不应该是 request.user 返回的内容吗?

最佳答案

使用 request.resource_owner 而不是 request.user

Django OAuth 工具包区分与不记名 token 关联的用户和与可能附加到请求的任何其他 Django 身份验证关联的用户。具体来说,ProtectedResourceView 包括来自 ProtectedResourceMixin 的行为,其中包括以下调度方法:

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()

关于python - Django oauth2 request.user 返回 AnonymousUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151064/

相关文章:

windows - Google 登录 oauth 集成在 Windows PWA 应用程序中不起作用

php - 无法使用 Oauth Google 发送 PHPMailer

python - 使用 App Engine 服务帐户时出现链接损坏错误

python - 使用Python实现串口延迟

python - PyAutoGui点击权限错误

python - 正则表达式 - HTML

python - Django开发: Chrome warns "Change Password"

python - 使用 apache solr 设置 Conceptnet

Django "view didn' t 返回一个 HttpResponse 对象。”

python - Django - 与模型无关的自定义管理页面