Are there any problems with creating the CSRF token with JavaScript just before submitting the form? Example:

var csrf_token = Math.random();

// Write csrf token to cookie.

// Add csrf token to the form being submitted.

// Submit form.

// Verify cookie csrf to form csrf on the server.

// When request is done; remove the cookie.

// Rinse and repeat.

I understand this is vulnerable to XSS but the XSS could just submit the form with custom values so having XSS is worse.


I would not recommend this. For the token to offer any protection, it must be unpredictable. Math.random() is not cryptographically secure - there is no guarantee that an attacker can not generate loads of random values, detect the pattern, and then deduce previous values thereby finding the value of the secret token. This is called "cross domain Math.random() prediction", and you can read more about it here and here.

I think (not sure, though) that most modern browsers protect against this in practice, but that is an implementation detail I would not bet the security of my application on. Actually, MDN warns against it:

Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

So can you just switch to getRandomValues()? Only if you are fine with 80% browser support.

Before doing this, ask yourself why you can't just generate the token on the server instead. If you go for the client approach anyway, at least avoid these two pitfalls:

  • Make sure that no token in the form and no token in the cookie does not pass! A naive equality check could let that pass, since both are an empty string, but that would open up a vulnerability.
  • There must be no URL that loads a page and automatically submits a form, adding the token in the process. Such an URL could be abused.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.