DEV Community

Discussion on: How to securely store JWT tokens.

Collapse
 
gkoniaris profile image
George Koniaris

If you store the cookie with HttpOnly flag, Secure flat and SameSite=Lax|Strict flag you are secure and good to go! This article assumes that you don't need access to the JWT content in the frontend, so it is ok to use the HTTP flag. So by setting the HttpOnly flag, the cookie can not be retrieved from Javascript, and by setting the SecureSite=Lax|Strict it won't be sent in cross-domain requests. Sorry if I was not 100% clear on this point.

Collapse
 
kevinhch profile image
Kevin

Ok, but if i need to get access from the frontend to make some request to my API in the backend, how should I get the token to authenticate my API calls from JS?

Thread Thread
 
gkoniaris profile image
George Koniaris

If your frontend is on the same domain as your API (or a first-level subdomain), the cookie should be automatically sent through Ajax requests. For example, if your web application is hosted on kevin.dev and your API is hosted on api.kevin.dev, the cookie will be sent in every Ajax request automatically. Of course, you should make your API fetch the cookie in the backend, and verify the token. In case you need to access the payload of the JWT token, that's not possible with HttpOnly cookies. You should make an extra request to your API, something like a /me endpoint, and save the data in a Javascript variable.

Thread Thread
 
kevinhch profile image
Kevin

Oh :O thnxs a lot, finally a good post to solve my problem!!