【问题标题】:Add custom field to Django Rest Framework generation token将自定义字段添加到 Django Rest Framework 生成令牌
【发布时间】:2019-10-22 12:22:59
【问题描述】:

使用 Django Rest 框架,当我想生成令牌时,我尝试添加一个自定义字段(氏族),它应该是必填字段和现有氏族。

喜欢:

curl -X POST -d "grant_type=password&username=username&password=password&client_id=client_id&client_secret=client_secret&clan=ABCDEF" http://localhost:8000/o/token/

我的用户模型:

class User(AbstractUser):
    """
    User model.
    """
    clans = models.ManyToManyField(Clan, related_name='Users')

我的休息框架设置:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'apps.core.api.pagination.StandardPagination',
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'EXCEPTION_HANDLER': 'apps.core.exceptions.api.custom_exception_handler',
}

那我想要一个经典的回应:

{
    "access_token": "azerty123456789",
    "expires_in": 36000,
    "token_type": "Bearer",
    "scope": "read write groups",
    "refresh_token": "azerty123456789"
}

【问题讨论】:

    标签: oauth-2.0 django-rest-framework


    【解决方案1】:

    终于找到了解决办法:

    您需要从 oauth2_provider.views.base 覆盖 TokenView 类,然后覆盖 post 方法

    class MyCustomToken(TokenView):
        """
        ....
        """
        @method_decorator(sensitive_post_parameters("password"))
        def post(self, request, *args, **kwargs):
            """
            ...
            """
            # Check if the clan parameter is given in parameter.
            clan_parameter = request.POST.get('clan', False)
            if not clan_parameter:
                return JsonResponse(
                    {'clan': 'Parameter is required.'},
                    status = 401
                )
            url, headers, body, status = self.create_token_response(request)
            if status == 200:
                access_token = json.loads(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)
            response = HttpResponse(content=body, status=status)
    
            for k, v in headers.items():
                response[k] = v
            return response
    

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 1970-01-01
      • 2019-02-03
      • 2013-01-13
      • 1970-01-01
      • 2015-09-25
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多