Search code examples
pythondjangoresthttp-headersapi-design

Django REST api calls and allowed_hosts


I'm trying to implement a RESTful API in Django such that any ip could query the endpoints. However, I'm concerned about header attacks if I were to set ALLOWED_HOSTS = ['*'].

I read an answer to Why is Django throwing error "DisallowedHost at /"? which suggests that api calls should be responded to, not for by the server.

I don't full comprehend what they mean or how to implement it and am looking for suggestions.

Ultimately, I want to know how can I make an api call which is not blocked by django because it is not in ALLOWED_HOSTS?


Solution

  • The problem you are having is not anything to do with ALLOWED_HOSTS, and everything to do with CSRF protection. You have two options. You can disable cross site request forgery protection on the page by using either

    @method_decorator(csrf_exempt, name=dispatch)
    

    above your class in django >= 1.9, or decorating the dispatch method in previous versions of django, such as this:

    class myView(View):
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
            return super(myView, self).dispatch(request, *args, **kwargs)
    

    If you are concerned about who can gain access though, you will need to look into other authentication methods, such as token based authentication, so that only sites passing the proper token can get access.