Generating Cryptographic Random State in JavaScript (in the Browser)
I need to generate some random state for an OAuth2 implicit flow for a JavaScript SPA. This “state” is passed to the identity provider, and then passed back after authentication to guard against XSS. Basically, I just need a string of random characters.
This state parameter is optional in OAuth2 implicit flow, and it only needs to be pseudo-random, but authentication isn’t something I like to take chances with, so I thought I’d look for the best option. I did a quick web search, as this seemed like the kind of thing that I’d find a perfect, best-practise, solution for on stack overflow, GitHub or similar. But, I had a few issues with the solutions I found:
- They used the
cryptolibrary from node, so were server-side solutions not intended for the browser, or, - They used
Math.randomwhich I decided wasn’t suitable and I wanted to use the Javascript Cryptography API, or, - They had nested loops and conditionals, which were either inefficient, or not declarative enough for my programming style, or,
- They produced a byte-string that didn’t encode easily in a URL.
Here was one of the implementations I liked, from an Angular OAuth2 library:





