Security in Node.js Applications: Using good cookie practices

Some nutritionists say eating too many sweets, such as cookies, is bad for your health. Web cookies, however, are widely used for many purposes including recording whether a browser is logged in or not. One common use is for cookies to store session data to aid in knowing whether someone is logged in or not.

In the Notes application, we’re already following the good practices described in the Express security guidelines:

  • We’re using an Express session cookie name different from the default shown in the documentation.
  • The Express session cookie secret is not the default shown in the documentation.
  • We use the express-session middleware, which only stores a session ID in the cookie, rather than the whole session data object.

Taken together, an attacker can’t exploit any known vulnerability that relies on the default values for these items. While it is convenient that many software products have default values, such as passwords, those defaults could be security vulnerabilities. For example, the default Raspberry Pi login/password is pi and raspberry. While that’s cute, any Raspbian-based IoT device that’s left with the default login/password is susceptible to attack.

But there is more customization we can do to the cookie used with express- session. That package has a few options available for improving security.

See https://www.npmjs.com/package/express-session, and then consider this change to the configuration:

app.use(session({

store: sessionStore,

secret: sessionSecret,

resave: true,

saveUninitialized: true,

name: sessionCookieName,

secure: true,

maxAge: 2 * 60 * 60 * 1000 // 2 hours

}));

These are additional attributes that look useful. The secure attribute requires that cookies be sent ONLY over HTTPS connections. This ensures the cookie data is encrypted by HTTPS encryption. The maxAge attribute sets an amount of time that cookies are valid, expressed in milliseconds.

Cookies are an extremely useful tool in web browsers, even if there is a lot of over- hyped worry about what websites do with cookies. At the same time, it is possible to misuse cookies and create security problems. In this section, we learned how to mitigate risks with the session cookie.

In the next section, we’ll review the best practices for AWS ECS deployment.

Source: Herron David (2020), Node.js Web Development: Server-side web development made easy with Node 14 using practical examples, Packt Publishing.

Leave a Reply

Your email address will not be published. Required fields are marked *