Skip to main content

JWT: How to securely stores cookies.

What is JWT?

JWT stands for JSON Web Token. It's a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

But... Let's skip the long words.

in short JWT or JSON Web Token is way to stores data safely and we're going to applies it cookies. So, let's get start.

  1. Let start with installing dependency.
    npm i jsonwebtoken
  2. Now let's create create new endpoint in /controllers/cookies/ called sendSecureCookie.js
    const jwt = require('jsonwebtoken');
    
    const SendSecureCookie = (req, res) => {
    	const key = 'myCookieButMorePrivate';
    	const value = 'This is some another private data';
    	const secret = 'mySecret';
    
    	try {
    		const token = jwt.sign({ value }, secret);
    		res.cookie(key, token);
    		res.send('Secure Cookie set');
    	} catch (error) {
    		console.error(error);
    		res.status(500).send('An error occurred, Secure Cookie not set');
    	}
    };
    
    module.exports = SendSecureCookie;
    

    as you see here, we're using jwtJWT to sign the data with our secret key. Right now, we're storing our secret value at the code. But the good practice would be to store it in .env file instead. (This will be graded as well be careful about your code security)

  3. Add /secure route to /routes/cookies.js file (Do it yourself or copy your friend whatever I will not provide the example this one)

  4. Now go to localhost:4000/cookies/secure to see the result.

    image.png


    As you will see there is another cookie appeared in the cookies list and now it is encoded to be more secure.

    You can take a look at jwt.io to see how it encoded.

    image.png



    Clearly some of you may confuse how is this secure when we can decode it in a website that everyone can access. The jwt.sign() process will sign the secret key to the data as a signature. Due to that even if we change the data value it will be invalid because it isn't sign with the original secret key. That mean the data cannot be changed.


    Try changing the signature to your secret key and paste the cookie value again. you will see that now if the secret key is correct, it is changeable. So again -- Keep your secret key secure in .env--