Abhishek Agarwal
Abhishek Agarwal

Reputation: 724

Send CSRF token to javascript

Suppose I maintain a anti CSRF token at server side in a session

How am I supposed to pass the token to client side application if my form generation is going to be dynamic(i.e. form will be created after some action has been performed by javascript)

Is there a way to pass the token to javascript so that I can inject the token in the form.

One working way that I found is send a cookie to the browser containing the token which will be then extracted by javascript.

Any suggestions?

Upvotes: 1

Views: 1851

Answers (2)

sebastian nielsen
sebastian nielsen

Reputation: 505

I would suggest starting out from a secure token, and then improving it through JavaScript according to dynamic form Creation.

Eg, like:

<input type="hidden" name="csrftoken" value="hgdillksdbgjksdbkvbskb">

Where the "value" parameter is generated on server-side when page loads.

And then you have a script like:

csrftoken = document.mainform.csrftoken.value;
# Do something with the CSRF token, like add dynamic values, like sha256(csrftoken + "dynamicvalue");
document.mainform.csrftoken.value = csrftoken;

The main idea of this, is to prevent, that even if they manage to get a exploit that would allow a adverisary to read the JavaScript code, they still cannot make up a valid CSRF token, since they cannot read the original "csrftoken" value that was inside the form at page load. This can also be used to "chain" AJAX requests, like that you start out with the token X during page load. Then you transform it to Y using JavaScript, send it in a AJAX request. In the next AJAX request, you can use Y as base in the algoritm, to create Z, and send to the server. A attacker cannot gain access to X, thus they cannot either get access to Y neither Z, even if they would in some way be able to exploit running JavaScript code to reveal itself.

Note that page contents cannot be read by a adversiary due to Same origin policy. But Javascript can contain exploits that would make it possible to read the actual running JavaScript code. Theres no such exploits currently, but better be safe than sorry.

Upvotes: 1

u2702
u2702

Reputation: 616

Sure. If you're dynamically generating the form on the client side then you're doing it from some kind of template. The token should be an argument to that creation function.

Pass the token along to the client at request/render time and then inject it into the form as a hidden element at form generation time.

Upvotes: 0

Related Questions