Step 18
Notice that you can edit the value of a cookie in developer tools:
You can even create a cookie, username
, and give it a value. That would mean tricking our app to think a user has already logged in.
One strategy to mitigate this issue is to "sign" (encrypt) the "username" cookie.
To make signed (encrypted) cookie, you must first provide an encryption key to the cookieParser
function:
app.use(cookieParser(process.env.ENCRYPT_KEY));
Update your .env
file and add an ENCRYPT_KEY
variable
DB_URI="YOUR-URI-GOES-HERE"
ENCRYPT_KEY="SOME_SECRET_PHRASE"
Next, you must provide an option when you create the "username" cookie to indicate you want this cookie to be signed:
- res.cookie("username", user.username).redirect(`/dashboard`);
+ res
+ .cookie("username", user.username, { signed: true })
+ .redirect(`/dashboard`);
Finally, you must change every instance of reading the "username" cookie, to read it as a signed cookie:
- const username = req.cookies.username;
+ const username = req.signedCookies.username;
Save the index.js
file. Log in using a valid credential and then investigate the cookie generated for the user. For example, I've logged in using the user name madooei
and this is the content of username
cookie on my browser:
s%3Amadooei.M5UVfPbyTAEE65zH1I401zdu4Kty6EQkkoncj1J1qyk
Notice the madooei
is still part of the cookie. If I manually change the cookie however, (for example, change the madooei
part to ali
) and refresh the dashboard, it will recognize that I have tampered with the cookie and take me to the login page.
A better, more secure, strategy to encode your cookies is using Json Web Token (JWT). We will not cover this here but you can read more about it following these resources: