Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protecting GET request within Django web application

How do I protect specific GET request (for example: ^api/...)?

I want to make this view (API call) available to only my Django web application.

It should only be called by Django web application, not directly.

Is it a good practice to use hash key generated by CSRF Middle-ware? Is there any better approach?

like image 826
abhiomkar Avatar asked Nov 03 '22 05:11

abhiomkar


1 Answers

I'm afraid that there are no reliable ways to achieve this. The best way I can think of, is generating some sort of private key in your javascript client, and ofuscate the code. That'd make it hard for "an attaker" to use your methods. Maybe using HMAC, or something like that.

An example. You want to make the following call: /api/users/1/vote_up. You could have some code to generate your private key:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js">

var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, generatePassphraseObfuscated());
hmac.update("/api/users/1/vote_up");
var hash = hmac.finalize();
$.ajax(
    /api/users/1/vote_up,
    {hash: hash}
)
</script>

The generatePassphraseObfuscated function is the key. You need to make it really hard to replicate. Also, you could change it in every request and add a cookie to identify which "version" you sent. For example, you could have two versions:

function generatePassphraseObfuscated(){
    return 1;
}

function generatePassphraseObfuscated(){
    return 2;
}

And serve them randomly, and identify it with a cookie. So you know which to use in your django view.

Again, it's not reliable, there's no foolproof way to do what you want to do. It's just a silly way to make it ugly for other people to replicate.

like image 78
santiagobasulto Avatar answered Nov 15 '22 05:11

santiagobasulto