"<p>In web development today, securing user sessions and data is a top priority. One popular way to handle this is with JSON Web Tokens (JWTs). But what exactly is a JWT? How does it work, and why does it have three distinct parts? More importantly, if you're planning to store JWTs in cookies, how can you ensure that they’re stored securely?</p> <p>This guide will walk you through the structure of a JWT, explain the importance of each part, and share tips on storing it safely to keep your web app secure.</p> <h4><strong>What Is a JWT and Why Use It?</strong></h4> <p>A JWT (JSON Web Token) is a compact and self-contained way to transmit information between parties securely. This information can be verified and trusted because JWTs are digitally signed. They’re frequently used for authentication purposes, where the server doesn’t need to store session state, making them particularly efficient for stateless APIs.</p> <p>A JWT consists of three key components:</p> <ol> <li><strong>Header</strong></li> <li><strong>Payload</strong></li> <li><strong>Signature</strong></li> </ol> <p><strong>1. Header</strong></p> <p>The header usually contains two fields:</p> <ul> <li><strong>alg</strong>: The signing algorithm used (like HMAC SHA256 or RSA)</li> <li><strong>typ</strong>: The type of token (which is "JWT" in this case)</li> </ul> <p>Here’s an example of a simple header:</p> <pre class="language-markup"><code>{ "alg": "HS256", "typ": "JWT" } </code></pre> <p>This header is then <strong>Base64Url</strong> encoded to make it URL-safe.</p> <p><strong>2. Payload</strong></p> <p>The payload holds the “claims.” Claims are the statements about an entity (typically the user) and additional data that might be needed by the application. There are a few types of claims:</p> <ul> <li><strong>Registered claims</strong>: These are standardized claims like <code>iss</code> (issuer), <code>exp</code> (expiration), <code>sub</code> (subject), etc.</li> <li><strong>Public claims</strong>: These are custom claims created by developers, specific to the application.</li> <li><strong>Private claims</strong>: Shared information between parties, like user data.</li> </ul> <p>An example payload might look like this:</p> <pre class="language-markup"><code>{ "sub": "1234567890", "name": "Jane Doe", "admin": true } </code></pre> <p>Like the header, the payload is also <strong>Base64Url</strong> encoded.</p> <p><strong>3. Signature</strong></p> <p>The signature is what makes the JWT secure. It's created by taking the encoded header and payload, combining them, and then signing the result with a secret or private key using the algorithm specified in the header.</p> <p>Here’s the formula:</p> <pre class="language-markup"><code>signature = HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret ); </code></pre> <p>The signature is critical because it ensures that the token hasn’t been altered. If anyone tries to tamper with the data in the token, the signature will no longer match, and the server will reject it.</p> <h4><strong>Why the Signature Matters</strong></h4> <p>While the header and payload are public and can be decoded by anyone, the signature is what guarantees the token’s integrity. Only the server knows the secret used to create the signature, and any change to the header or payload would break the signature.</p> <p>For example, if an attacker tried to modify the <code>admin</code> field in the payload to change their permissions, they wouldn’t be able to generate a new valid signature without access to the secret key. This is why the signature is so important—it ensures that the token’s data is trustworthy.</p> <h4><strong>Best Practices for Storing JWT in Cookies</strong></h4> <p>When storing JWTs on the client-side, there are two common storage options: <strong>localStorage</strong> and <strong>cookies</strong>. If you decide to use cookies, you need to apply some important security measures to protect the token from potential attacks.</p> <p><strong>1. HttpOnly Flag</strong></p> <p>The <code>HttpOnly</code> flag ensures that the cookie can’t be accessed via JavaScript, which helps prevent it from being stolen through cross-site scripting (XSS) attacks.</p> <div class="flex-shrink-0 flex flex-col relative items-end"> <div> <div class="pt-0"> <div class="gizmo-bot-avatar flex h-8 w-8 items-center justify-center overflow-hidden rounded-full"> </div> </div> </div> </div> <div class="group/conversation-turn relative flex w-full min-w-0 flex-col agent-turn"> <div class="flex-col gap-1 md:gap-3"> <div class="flex max-w-full flex-col flex-grow"> <div class="min-h-8 text-message flex w-full flex-col items-end gap-2 whitespace-normal break-words [.text-message+&]:mt-5" dir="auto" data-message-author-role="assistant" data-message-id="8c1a8686-dccf-483b-9adf-579d22aa5986" data-message-model-slug="gpt-4o"> <div class="flex w-full flex-col gap-1 empty:hidden first:pt-[3px]"> <div class="markdown prose w-full break-words dark:prose-invert dark"> <p><strong>2. Secure Flag</strong></p> <p>Setting the <code>Secure</code> flag ensures the cookie is only sent over HTTPS, which protects it from being intercepted over unencrypted HTTP connections.</p> <p><strong>3. SameSite Attribute</strong></p> <p>The <code>SameSite</code> attribute is designed to prevent cross-site request forgery (CSRF) attacks by controlling how and when cookies are sent with requests. Setting this to <code>Strict</code> or <code>Lax</code> will help ensure the cookie is only sent in a controlled manner.</p> <h4><strong>Conclusion</strong></h4> <p>JWTs offer a lightweight and secure method for handling authentication in modern web applications. By understanding the structure of JWTs—header, payload, and signature—you can see how they work and why they’re effective.</p> <p>Equally important is how you store your JWT. When using cookies, always apply security options like <code>HttpOnly</code>, <code>Secure</code>, and <code>SameSite</code> to ensure your tokens are well-protected. Following these best practices helps safeguard your users and keeps your application secure from common web threats.</p> <p>By paying close attention to both JWT structure and storage, you’ll be well on your way to building a more secure authentication system.</p> </div> </div> </div> </div> </div> </div>"