Skip to content

Instantly share code, notes, and snippets.

@amitmbee
Created June 18, 2020 12:36
Show Gist options
  • Save amitmbee/a93b877d284f17e5fa470e9488e19e0d to your computer and use it in GitHub Desktop.
Save amitmbee/a93b877d284f17e5fa470e9488e19e0d to your computer and use it in GitHub Desktop.
jwt cookies

You have the following options -

Cookies Local Storage or Session Storage In Javascript variables Storing JWT in cookies is largely equivalent to Django's cookie based sessions. If you are in control of the server, then you might as well use that instead.

But if you are not in control of the server, or if you have to use JWT for some reason - it is sill better to store the JWT in a cookie rather than local storage. Cookies have two security properties - IsSecure flag, and HttpOnly. IsSecure flag instructs browsers to send the cookie over HTTPS only. HttpOnly makes the cookie inaccessible using javascript code. These are designed to protect users of your application.

Cookies are automatically sent to the server with every request. If the server requires the JWT as part of an Authorization header, cookies won't work automatically. You will have to use javascript to extract the token from the cookie, and explicitly set it as a request header. This has two drawbacks - firstly you are sending the cookie twice (implicit cookie and explicit request header), and secondly you cannot use the HttpOnly flag because you have to use javascript to read the cookie.

In such cases, it may be better to use Local Storage / Session Storage.

Finally, a third option is to store the token in memory. This means that on refresh you won't have the token. This is a valid strategy if the server generates the JWT as part of the intial payload and makes it available somewhere in the DOM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment