Session Management
Vibe Prompt
「幫我實作安全的 Session 管理:HTTP-only、Secure、SameSite Cookie,Session 儲存在 Redis。」
安全 Cookie 設定
// Express
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, // JavaScript 無法讀取
secure: true, // 僅 HTTPS
sameSite: 'strict', // 防止 CSRF
maxAge: 24 * 60 * 60 * 1000, // 24 小時
},
}));
Redis Session Store
import Redis from 'ioredis';
import session from 'express-session';
import RedisStore from 'connect-redis';
const redis = new Redis({
host: process.env.REDIS_HOST,
port: 6379,
password: process.env.REDIS_PASSWORD,
});
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SESSION_SECRET,
cookie: {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 86400000,
},
}));
Session Fixation 防護
// 登入後重新生成 Session ID
app.post('/login', async (req, res) => {
const user = await authenticate(req.body);
if (user) {
req.session.regenerate((err) => {
req.session.userId = user.id;
res.json({ success: true });
});
}
});