Skip to content

Instantly share code, notes, and snippets.

@bhowe
Created January 18, 2026 12:39
Show Gist options
  • Select an option

  • Save bhowe/eb73446ce6d0ca0d311436e71dbf1cd5 to your computer and use it in GitHub Desktop.

Select an option

Save bhowe/eb73446ce6d0ca0d311436e71dbf1cd5 to your computer and use it in GitHub Desktop.
// Session Hijacking Prevention - Code Examples
// 1. SECURE COOKIE CONFIGURATION
// Set proper cookie flags to prevent various attacks
res.cookie('sessionId', sessionToken, {
httpOnly: true, // Prevents JavaScript access (XSS protection)
secure: true, // Only sent over HTTPS
sameSite: 'strict', // Prevents CSRF attacks
maxAge: 3600000 // Expire after 1 hour
});
// 2. REGENERATE SESSION IDS AFTER LOGIN
// Prevents session fixation attacks
app.post('/login', (req, res) => {
// Authenticate user first
req.session.regenerate((err) => {
if (err) {
return res.status(500).send('Session error');
}
// Create new session ID
req.session.userId = user.id;
res.redirect('/dashboard');
});
});
// 3. IMPLEMENT SESSION TIMEOUTS
// Expire inactive sessions automatically
const SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
function checkSessionExpiry(session) {
if (Date.now() - session.lastActivity > SESSION_TIMEOUT) {
session.destroy();
return false;
}
session.lastActivity = Date.now();
return true;
}
// Middleware to check session on each request
app.use((req, res, next) => {
if (req.session && !checkSessionExpiry(req.session)) {
return res.status(401).send('Session expired');
}
next();
});
// 4. VALIDATE SESSION CONTEXT
// Check IP address and user agent for potential hijacking
function validateSession(req, session) {
if (session.ipAddress !== req.ip ||
session.userAgent !== req.headers['user-agent']) {
// Potential hijacking detected - destroy session
session.destroy();
return false;
}
return true;
}
// Store initial context on login
app.post('/login', (req, res) => {
req.session.ipAddress = req.ip;
req.session.userAgent = req.headers['user-agent'];
// ... rest of login logic
});
// 5. INPUT SANITIZATION (XSS PREVENTION)
// Escape user input before displaying
function escapeHtml(text) {
const map = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.replace(/[&<>"']/g, m => map[m]);
}
// Usage example
app.get('/profile', (req, res) => {
const userInput = req.query.name;
const safeName = escapeHtml(userInput);
res.send(`<h1>Welcome ${safeName}</h1>`);
});
// 6. CONTENT SECURITY POLICY HEADERS
// Prevent inline scripts and restrict content sources
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
);
next();
});
// 7. RATE LIMITING ON LOGIN ATTEMPTS
// Prevent brute force attacks
const rateLimit = require('express-rate-limit');
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Limit each IP to 5 requests per windowMs
message: 'Too many login attempts, please try again later'
});
app.post('/login', loginLimiter, (req, res) => {
// Login logic here
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment