Tips & Tricks

Claude CodeでCookie・セッション管理を実装する方法

Claude Codeを使ってCookieの安全な設定・セッション管理・CSRF対策を効率的に実装する方法を解説します。

Cookie管理の重要性

Cookieはユーザー認証やセッション管理の基盤ですが、セキュリティの設定ミスは深刻な脆弱性につながります。Claude Codeを使えば、セキュアなCookie管理の仕組みを正しく実装できます。

安全なCookie操作ユーティリティ

> セキュリティ設定を含めたCookie操作のユーティリティを作って。
> HttpOnly, Secure, SameSiteの設定を必須にして。
interface CookieOptions {
  maxAge?: number;
  path?: string;
  domain?: string;
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: 'strict' | 'lax' | 'none';
}

const DEFAULT_OPTIONS: CookieOptions = {
  path: '/',
  secure: true,
  httpOnly: true,
  sameSite: 'lax',
  maxAge: 86400, // 1日
};

class CookieManager {
  static set(name: string, value: string, options: CookieOptions = {}) {
    const opts = { ...DEFAULT_OPTIONS, ...options };
    const parts = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];

    if (opts.maxAge) parts.push(`Max-Age=${opts.maxAge}`);
    if (opts.path) parts.push(`Path=${opts.path}`);
    if (opts.domain) parts.push(`Domain=${opts.domain}`);
    if (opts.secure) parts.push('Secure');
    if (opts.httpOnly) parts.push('HttpOnly');
    if (opts.sameSite) parts.push(`SameSite=${opts.sameSite}`);

    return parts.join('; ');
  }

  static parse(cookieHeader: string): Record<string, string> {
    return cookieHeader.split(';').reduce((acc, pair) => {
      const [key, ...vals] = pair.trim().split('=');
      if (key) acc[decodeURIComponent(key)] = decodeURIComponent(vals.join('='));
      return acc;
    }, {} as Record<string, string>);
  }

  static delete(name: string, path = '/') {
    return this.set(name, '', { maxAge: 0, path });
  }
}

Expressでのセッション管理

> Expressでセキュアなセッション管理を実装して。
> RedisをセッションストアにしてCSRF対策も入れて。
import session from 'express-session';
import RedisStore from 'connect-redis';
import { createClient } from 'redis';
import csrf from 'csurf';

const redisClient = createClient({ url: process.env.REDIS_URL });
redisClient.connect();

const sessionConfig: session.SessionOptions = {
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET!,
  name: '__session',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: process.env.NODE_ENV === 'production',
    httpOnly: true,
    sameSite: 'lax',
    maxAge: 24 * 60 * 60 * 1000, // 24時間
  },
};

app.use(session(sessionConfig));
app.use(csrf({ cookie: false })); // セッションベースのCSRF

クライアント側の安全なCookie操作

ブラウザ側で操作するCookie(HttpOnlyでないもの)の管理もClaude Codeで生成できます。

// クライアント側のCookieユーティリティ(テーマや言語設定など非機密情報用)
export const clientCookie = {
  get(name: string): string | null {
    const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
    return match ? decodeURIComponent(match[1]) : null;
  },

  set(name: string, value: string, days = 365) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};expires=${expires};path=/;SameSite=Lax`;
  },

  remove(name: string) {
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
  },
};

// 使用例:テーマ設定の保存
clientCookie.set('theme', 'dark');
const theme = clientCookie.get('theme'); // 'dark'

セッションのセキュリティ強化

// セッション固定攻撃の防止
app.post('/login', async (req, res) => {
  const user = await authenticate(req.body);

  // ログイン成功時にセッションIDを再生成
  req.session.regenerate((err) => {
    if (err) return res.status(500).json({ error: 'セッションエラー' });
    req.session.userId = user.id;
    res.json({ success: true });
  });
});

まとめ

Claude Codeを使えば、セキュアなCookie設定からセッション管理、CSRF対策まで一貫して実装できます。認証全般については認証実装ガイドを、JWT認証との比較はJWT認証の記事を参照してください。セキュリティの詳細はセキュリティ監査も参考になります。

セッション管理のベストプラクティスはOWASP Session Managementをご覧ください。

#Claude Code #Cookie #セッション #セキュリティ #TypeScript