DEV Community

Discussion on: Cookies Vs Local storage Vs Session storage

Collapse
 
cubikca profile image
Brian Richardson

None of them are secure, so don't go storing unencrypted secrets there. I've used both cookies and local storage in the past, but this is the first I've heard about session storage 😀.

It seems like a matter of scope and convenience. Cookies are convenient, being sent automatically provided that the domains match up. In authentication scenarios, cookies and bearer tokens can be used interchangeably, and the cookie might save you some coding. However, in cases where the domain doesn't line up, you'll need to use bearer tokens instead, which can be saved to local storage along with the refresh token.

The only difference, then, is whether you want your client app data to be stored beyond the browser session or not. This seems to be something you could control with a "Remember"-type option. Overall, all three have their uses. And cookies are not exclusive of the other two. But none of them are inherently secure, so ensure that you store only encrypted data in all these locations.

Collapse
 
nermineslimane profile image
nermineslimane

so what do you suggest can be the most secure option to authenticate a user using jwt tokens?

Collapse
 
cubikca profile image
Brian Richardson

I guess it would help to look at what you are actually trying to prevent. In my case, I'm interested in ensuring that an application user who accesses the application on a public terminal is not exposing their credentials to the next terminal user. The terminal user may: have access to your browser session if you forgot to close the browser; have access to your cookies; have access to your local storage. As you can see, all of these locations are potentially readable by another user of the terminal. A JWT is transferrable (though it does expire), so the next terminal user has the lifetime of the JWT to use it maliciously.

The description above is what I meant when I said "insecure". You cannot prevent another user from reading these storage locations. Therefore, you need to encrypt any sensitive data that goes in there, including your JWT. At some point though, you can only obfuscate it, because you'll have to put the encryption key somewhere on the client side too.

One method I've used to guard against the transferabiliity of JWTs is to include an HMAC signature and nonce with each request. That way, each request can only be used once and the JWT is not immediately useful to someone who intercepts it. This gets into more advanced cryptography though, and is maybe more than you need to worry about for most applications.