Session validation is essential to preserving your web application's security. Here, we'll go over suggested practices for handling session tokens and cookies, securely invalidating sessions, and giving examples with well-known frameworks like Express and Django.
Methods for Session Invalidation
1. Server-Side Invalidation:
- Remove Session Data: Clear off the related session data from your file system, database, or cache.
- Regenerate Session ID (Optional): To guard against session fixation attacks, regenerate a session ID if you're using one.
2. Client-Side Invalidation:
- Expire/Remove Session Cookies: Either erase the session cookie completely or set its expiration date to a previous date.
- Revoke Token (Token-based Sessions): Make sure the token is invalidated on the server side and deleted from the client's storage (such as cookies and local storage) if you're utilizing token-based sessions.
Managing Session Tokens/Cookies
1. Session Cookies
- Use Secure and HttpOnly Flags: To guarantee transmission over HTTPS, set the Secure flag; to block JavaScript access, set the HttpOnly flag.
- Set Proper Expiration: To strike a balance between security and user convenience, choose a fair expiration date.
- Use a Secure Random Session ID: Create session IDs with a pseudo-random number generator (CSPRNG) that is cryptographically secure.
2. Token-based Sessions
- Store Tokens Securely on the Client-Side: Use secure storage methods, such as HTTPS-only cookies or encrypted local storage.
- Validate Tokens on Each Request: On each request that comes in, confirm the signature and expiration date of the token.
- Use Short-Lived Tokens: To reduce the attack window, use token rotation or renewal.
Framework-Specific Examples
1. Express.js (Node.js)
Using express-session middleware:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your_secret_key',
resave: false,
saveUninitialized: true,
cookie: {
secure: true, // Set to true when using HTTPS
httpOnly: true,
expires: new Date(Date.now() + (30 * 60 * 1000)) // 30 minutes
}
}));
// Invalidate session on logout
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.log(err);
} else {
res.clearCookie('connect.sid'); // Remove session cookie
res.redirect('/login');
}
});
});
2. Django (Python)
Using Django's built-in session framework:
# settings.py
SESSION_COOKIE_SECURE = True # Set to True when using HTTPS
SESSION_COOKIE_HTTPONLY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # or set SESSION_TIMEOUT
# views.py
from django.contrib.auth import logout
from django.http import HttpResponse
def logout_view(request):
logout(request)
response = HttpResponse('Logged out successfully')
response.delete_cookie('sessionid') # Remove session cookie
return response