3
votes

I'm following this tutorial on JWT using GraphQL.

In that tutorial,

What about saving it in a cookie?

Creating cookies on the client to save the JWT will also be prone to XSS. If it can be read on the client from Javascript outside of your app - it can be stolen. You might think an HttpOnly cookie (created by the server instead of the client) will help, but cookies are vulnerable to CSRF attacks. It is important to note that HttpOnly and sensible CORS policies cannot prevent CSRF form-submit attacks and using cookies require a proper CSRF mitigation strategy.

So the author saves the JWT in in-memory(variable).

But I read on this SO post that javascript can read other variables.

XSS happens when the attacker can run Javascript on the website. If there is an XSS vulnerability, then the attacker can read/set cookies, transfer details of the user to the attacker server by reading the javascript variables. So, how can saving JWT in in-memory safer than storing in Local Storage or cookies?

Am I missing something? (I might be because I've searched for this and I got nothing on the internet.)

1

1 Answers

3
votes

Storing JWTs in-memory still leaves them vulnerable to XSS but it makes it a bit harder to retrieve the tokens.

Lets assume you are using a malicious library in your code. If you store the tokens in localStorage the library could just dumb everything in it and send it somewhere else. This attack will work on any website which stores tokens in localStorage. If you are storing the tokens in-memory the attacker needs to target your application specifically since additional implementation details are required.

I would not recommend storing tokens in-memory but instead use HttpOnly cookies which protects the tokens from XSS. Now you only need to worry about CSRF which can be achieved in modern browsers by simply setting the SameSite attribute of the cookies to Lax or you could additionally use CSRF tokens.