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
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.