0

Is a react component's state susceptible to XSS?

I'm wondering if storing a JWT access token in a component's state is any less dangerous than in localStorage?

Deekor
  • 9,144
  • 16
  • 69
  • 121
  • I don't have an answer on the security of using state, but I wanted to point out that with that approach, a page reload will clear the token – ChiefMcFrank Jan 30 '22 at 06:25
  • @ChiefMcFrank ya I'm aware. The token is pulled from a web request (auth0) and can lag a second or two. I wanted to use the state variable as a way to wait for the token AND THEN make an API request. – Deekor Jan 30 '22 at 06:30

1 Answers1

3

Depending on how the state is used and set, it can be less susceptible, but it's not foolproof.

If you're worried about untrustworthy code possibly accessing what they shouldn't, one of the issues with Local Storage is that any script running on the page can easily access any value in Local Storage for that domain. In contrast, a value which is in React state somewhere, by itself, is a whole lot more difficult to access.

If the state is used externally from the component anywhere, it's potentially susceptible to interception by malicious scripts. For example, if the state is used in an API request, a malicious script could patch window.fetch or window.XMLHttpRequest and spy on it (unless you take precautions against those too). And if the state is put onto the page, such as in an input (even if hidden), it'd be trivial for a malicious script to retrieve it.

Even if the state isn't used directly anywhere, in some circumstances, it's also barely possible to gain access to the closure in which it's defined or set.

Generally, if malicious code runs on a page, you can't count on anything else running on the page being secure. The best first approach would be to make sure your app doesn't have any XSS vulnerabilities in the first place. Guarding against such possibilities should be a distant second priority.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • thats a good point - if they can patch `window.fetch` it doesn't matter where I store the token if I'm going to be sending it over with a request to a backend api – Deekor Jan 30 '22 at 06:34
  • You can guard against it by doing your best to run your script first, before any other possible script on the page could run, and save `window.fetch` and other needed built-ins in a variable first, so that later scripts overwriting it wouldn't have any effect. Another weird option would be to create an iframe (with its own clean environment) and send from there. – CertainPerformance Jan 30 '22 at 06:36