Implement secure session management
✓Works with OpenClaudeYou are a backend security engineer. The user wants to implement secure session management with proper token handling, expiration, and storage.
What to check first
- Verify your web framework supports middleware (Express, FastAPI, Django, etc.)
- Run
npm list jsonwebtoken express-sessionor equivalent to confirm session libraries are installed - Check if you have a database or Redis instance available for session storage
Steps
- Install session middleware:
npm install express-session connect-mongo(for MongoDB) ornpm install express-sessionwith memory store for development - Configure session middleware with secure defaults: httpOnly, secure (HTTPS only), sameSite=strict, and maxAge in milliseconds
- Generate cryptographically secure session IDs using the framework's built-in methods (not manual string generation)
- Implement session store that persists to database or Redis, not in-memory for production
- Set up session regeneration on login to prevent session fixation attacks
- Create session destruction on logout that clears all session data and invalidates tokens
- Implement session timeout and idle timeout with automatic re-authentication prompts
- Add CSRF token generation and validation tied to the session ID
Code
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const app = express();
// Middleware setup
app.use(cookieParser('your-secret-key'));
app.use(express.urlencoded({ extended: false }));
// Session configuration
app.use(session({
secret: process.env.SESSION_SECRET,
store: new MongoStore({
url: process.env.MONGO_URI,
collectionName: 'sessions',
ttl: 24 * 60 * 60 // 24 hours
}),
name: 'sessionId',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, // Prevent XSS access
secure: true, // HTTPS only
sameSite: 'strict', // CSRF protection
maxAge: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
domain: 'yourdomain.com'
},
rolling: true // Refresh session on each request
}));
// CSRF protection
const csrfProtection = csrf({ cookie: false });
app.use(csrfProtection);
// Login route with session regeneration
app.post('/login', async (req, res) => {
const { username, password } = req.body;
// Verify credentials (implementation depends on your auth system)
const user = await authenticateUser(username, password);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Authentication Skills
Other Claude Code skills in the same category — free to download.
JWT Auth
Implement JWT authentication from scratch
OAuth Setup
Set up OAuth 2.0 with multiple providers
NextAuth Setup
Configure NextAuth.js/Auth.js
Passport Setup
Set up Passport.js with strategies
Magic Link Auth
Implement passwordless magic link auth
Two Factor Auth
Add 2FA/MFA to authentication flow
API Key Auth
Create API key authentication system
SSO Setup
Set up Single Sign-On (SAML/OIDC)
Want a Authentication skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.