Why should I store JWT token in cookie?
I understand that this approach prevent Cross-Site Scripting (XSS) attacks and it is more secure than local storage. But what if user can simply look at JWT in dev tools and see the token, is that a real problem?
CodePudding user response:
Fundamentally, if you want to store data on the client-side somewhere, the client will be able to see it themselves if they're determined enough. There's no way to store data on a client's machine without the client being able to use their machine to find and look at it.
If you store the JWT in an HttpOnly cookie, it'll be more secure than other methods because then it won't be possible for malicious scripts to scrape the credentials. Like you've noticed, the client will still be able to read it manually - but that's usually considered OK. The alternative, if no data can be stored on the client, is to require that the client supply their credentials with every request - but without storage, that'd be cumbersome to the point of making a system unusable. It's also a odd attack vector for someone to manually take a JWT from a browser that isn't theirs, though it's not impossible.
So - it's a potential small problem in unusual circumstances (which can be mitigated to some extent by performing more verification methods on the server, like checking the originating network and fingerprinting the browser), but the alternative of not being able to store anything on the client at all may be worse.
Depending on what you're storing on the JWT, you're free to encrypt it so that only your server can decode it. That way, even if someone with access to the client machine tries to mess with it, all they'll be able to do is to copy it verbatim or delete it; they won't be able to modify it.