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 });
    });
  }
});

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!