python - django-oauth-工具包 : Customize authenticate response

标签 python django django-rest-framework django-oauth django-oauth-toolkit

我是 Django OAuth 工具包的新手。我想自定义身份验证响应。

我在 Django 应用程序上的身份验证 url 配置是:

url('authenticate/',
    include('oauth2_provider.urls', namespace='oauth2_provider'))

https://django-oauth-toolkit.readthedocs.io/en/latest/install.html

现在,当我启动此命令时:
curl -X POST -d 'grant_type=password&username=$username&password=$password'
 -u "$client_id:$client_secret" http://127.0.0.1:8000/authenticate/token/

我得到这个回应:
{
   "access_token": "ATiM10L0LNaldJPk12drXCjbhoeDR8",
   "expires_in": 36000,
   "refresh_token": "II4UBhXhpVDEKWmsUQxDzkj3OMjW1p",
   "scope": "read groups write",
   "token_type": "Bearer"
}

并希望得到这样的回应:
{
   "access_token": "ATiM10L0LNaldJPk12drXCjbhoeDR8",
   "expires_in": 36000,
   "refresh_token": "II4UBhXhpVDEKWmsUQxDzkj3OMjW1p",
   "scope": "read groups write",
   "token_type": "Bearer",
   "member": {
      "id": 1,
      "username": "username",
      "email": "email@gmail.com",
      ....
   }
}

我只想覆盖此响应以添加经过身份验证的用户的信息。
我已经阅读了 django-oauth-toolkit 的文档。而且我没有找到解决我的问题的方法...

最佳答案

我能够通过覆盖 TokenView 类来进行此更改
在您的 views.py

from django.http import HttpResponse
from oauth2_provider.views.base import TokenView
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from oauth2_provider.models import get_access_token_model, get_application_model
from oauth2_provider.signals import app_authorize

class CustomTokenView(TokenView):
    @method_decorator(sensitive_post_parameters("password"))
    def post(self, request, *args, **kwargs):
        url, headers, body, status = self.create_token_response(request)
        if status == 200:
            body = json.loads(body)
            access_token = body.get("access_token")
            if access_token is not None:
                token = get_access_token_model().objects.get(
                    token=access_token)
                app_authorized.send(
                    sender=self, request=request,
                    token=token)
                body['member'] = {
                    'id': token.user.id, 
                    'username': token.user.username, 
                    'email': token.user.email
                }
                body = json.dumps(body) 
        response = HttpResponse(content=body, status=status)
        for k, v in headers.items():
            response[k] = v
        return response

urls.py ,只需通过指向自定义 View 覆盖 token url。此导入应在包含 django-oauth-toolkit 之前
url(r"authenticate/token/$", CustomTokenView.as_view(), name="token"),
url('authenticate/',
    include('oauth2_provider.urls', namespace='oauth2_provider'))

返回现在将包含成员数据
  {
    "access_token": "YtiH9FGwAf7Cb814EjTKbv3FCpLtag", 
    "expires_in": 36000, 
    "token_type": "Bearer", 
    "scope": "read write groups", 
    "refresh_token": "99TyWmCwELrJvymT8m6Z9EPxGr3PJi", 
    "member": {
        "id": 1, 
        "username": "admin", 
        "email": "admin@admin.com"
     }
  }

关于python - django-oauth-工具包 : Customize authenticate response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54370004/

相关文章:

django - DRF : custom ordering on related serializers

Django - 为什么syncdb不尊重数据库路由器?

django - DRF如何获取按类别分组的项目

django - 如何自定义 JWT 响应的负载部分

python - Matplotlib 下标

python - 如何将异常中的默认消息更改为自定义消息?

python - 根据条件将一个 python pandas 数据帧列的值替换为另一列的值

python - 将 3D 数组切成多个 2D 数组

python - 删除前导和尾随斜杠/在python中

python - 序列化器的 to_representation 能否在 DRF 3 中生成多个输出项?