代码之家  ›  专栏  ›  技术社区  ›  darkhorse

如何使用Django Rest框架接受来自特定域的请求?

  •  0
  • darkhorse  · 技术社区  · 5 年前

    whitelisted_domain 由用户设置。当请求命中其中一个项目时,我要确保该请求来自白名单域。例如:

    class CreateTask(APIView):
        def post(self, request, project_id, format=None):
            project = Project.objects.get(id=project_id)
            # Here, I want to check if the two domains match or not
            if project.whitelisted_domain == request.META['REMOTE_HOST']:
                # Create task
            else:
                # Raise authentication error
    

    0 回复  |  直到 5 年前
        1
  •  0
  •   darkhorse    5 年前

    你可以白名单IP。然后检查IP是否白名单。

    def get_client_ip(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = '127.0.0.1' # check if localhost.
        return ip
    

    在您的视图中.py:

    if project.whitelisted_domain == get_client_ip(request):
            # Create task
        else:
            # Raise authentication error