JAVASCRIPT
Set Secure Cookie Attributes (HttpOnly, Secure, SameSite)
Learn to configure essential security attributes like HttpOnly, Secure, and SameSite for cookies in Express.js, enhancing protection against XSS and CSRF attacks.
// This example assumes an Express.js application.
const express = require('express');
const app = express();
const port = 3000;
app.get('/login', (req, res) => {
// In a real application, after successful authentication:
// Set a session cookie with critical security flags
res.cookie('session_token', 'random_secure_token_value', {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: true, // Ensures the cookie is only sent over HTTPS
sameSite: 'Lax',// Mitigates CSRF attacks; 'Strict' is stronger, 'None' requires 'Secure'
maxAge: 3600000, // Cookie expires in 1 hour (in milliseconds)
path: '/', // The path for which the cookie is valid
// domain: '.example.com' // Specify if the cookie should be shared across subdomains
});
res.send('Logged in! A secure cookie has been set.');
});
app.get('/logout', (req, res) => {
// Clear the cookie when logging out
res.clearCookie('session_token', {
httpOnly: true,
secure: true,
sameSite: 'Lax',
path: '/'
});
res.send('Logged out! Cookie cleared.');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to set essential security attributes for HTTP cookies. The `httpOnly` flag prevents client-side JavaScript from accessing the cookie, effectively mitigating XSS attacks. The `secure` flag ensures the cookie is only sent over HTTPS connections, protecting against man-in-the-middle attacks. The `sameSite` attribute helps prevent Cross-Site Request Forgery (CSRF) attacks by controlling when browsers send cookies with cross-site requests. 'Lax' is a good default, while 'Strict' provides stronger protection (but can have usability impacts), and 'None' requires the `secure` flag and explicit intent for cross-site usage. These attributes are crucial for securing session tokens and other sensitive cookie data.