DjangoHack: How to specify HTTP methods to certain origin.

Ruhshan Ahmed Abir
2 min readJul 1, 2018

There are many layer of security for your web project. Today I’m going to write about a form of application layer security which I think also a form of secure by design.

There was a service I was working on. Different other services was using that service. Initially all the other services had access to both reading and writing data to that service. But after a redesign and implementing more granularity it appeared that only two services are writing with POST and PUT and other are reading with GET method.

Though those services were using proper credentials but I though how it can be configured such a way that a POST request will be revoked even before it reaches the authenticate module. That might secure my service even if both the url and credentials get leaked.

So I created a middleware, and in that file I created a dictionary of remote address and its allowed methods like this:

method_remote = ['POST':'127.0.0.1', 'GET':'127.0.0.2']

The functionality of the middleware was like this:

That’s it. Whenever a request comes it passed down to this middleware. This middleware iterates over a list of http methods. When the method of incoming request matches with the method of current iteration, it checks in the dictionary that is it that same as specified or not and responds accordingly.

You can also use this script if you have a similar use case. Please suggest if you know or thought of any better way of doing this.

I’ve also packaged this project in an app available from pypi . So that you can use this with minimal effort like this:

1. pip install django-restrictmethodorigin2. Add "restrictmethodorigin" to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
...
'restrictmethodorigin',
]
3. Add "OriginRestrictor" to your MIDDLEWARE like this:
MIDDLEWARE = [
...
'restrictmethodorigin.base.OriginRestrictor'
]
4. In settings.py create a dictionary METHOD_ORIGIN like this:
METHOD_ORIGIN = { 'POST': ['127.0.0.1'],
'PUT': ['127.0.0.1','127.0.0.2'] }

Happy coding!

--

--

Ruhshan Ahmed Abir

Started with poetry, ended up with codes. Have a university degree on Biotechnology. Works and talks about Java, Python, JS. www.buymeacoffee.com/ruhshan