Tips & Tricks

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

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

Cookie管理の重要性

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

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

HTTPのCookie自体は単なるヘッダなので、クラス名のsetを呼んでも実際にはレスポンスには届きません。下記ユーティリティは以下の2層構成にしています。

  • buildSetCookieHeader : Set-Cookie ヘッダ文字列を組み立てる 純粋関数
  • CookieManager : http.ServerResponse / Express Response を受け取り、実際にレスポンスヘッダに書き込む
> セキュリティ設定を含めたCookie操作のユーティリティを作って。
> HttpOnly, Secure, SameSiteの設定を必須にして。
> レスポンスオブジェクトに実際にヘッダを追加する実装にしたい。
import type { ServerResponse } from 'node:http';
import type { Response } from 'express';

export interface CookieOptions {
  maxAge?: number;
  path?: string;
  domain?: string;
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: 'strict' | 'lax' | 'none';
}

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

/** Set-Cookie ヘッダ文字列を組み立てる純粋関数(テスト容易) */
export function buildSetCookieHeader(
  name: string,
  value: string,
  options: CookieOptions = {},
): string {
  const opts = { ...DEFAULT_OPTIONS, ...options };
  const parts = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];

  if (typeof opts.maxAge === 'number') 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) {
    // SameSite=None は Secure 必須(仕様)
    if (opts.sameSite === 'none' && !opts.secure) {
      throw new Error('SameSite=None の場合は Secure も必須です');
    }
    parts.push(`SameSite=${opts.sameSite.charAt(0).toUpperCase() + opts.sameSite.slice(1)}`);
  }

  return parts.join('; ');
}

/** 既存の Set-Cookie ヘッダを壊さずに追記する */
function appendSetCookie(res: ServerResponse, header: string) {
  const existing = res.getHeader('Set-Cookie');
  if (Array.isArray(existing)) {
    res.setHeader('Set-Cookie', [...existing, header]);
  } else if (typeof existing === 'string') {
    res.setHeader('Set-Cookie', [existing, header]);
  } else {
    res.setHeader('Set-Cookie', header);
  }
}

export class CookieManager {
  /** 実際に res オブジェクトに Set-Cookie ヘッダを追加する */
  static set(
    res: ServerResponse | Response,
    name: string,
    value: string,
    options: CookieOptions = {},
  ): void {
    const header = buildSetCookieHeader(name, value, options);
    appendSetCookie(res as ServerResponse, header);
  }

  /** Cookieヘッダ文字列をパースして key-value に展開 */
  static parse(cookieHeader: string | undefined): Record<string, string> {
    if (!cookieHeader) return {};
    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>);
  }

  /** Max-Age=0 で即座に削除 */
  static delete(
    res: ServerResponse | Response,
    name: string,
    options: Pick<CookieOptions, 'path' | 'domain'> = {},
  ): void {
    CookieManager.set(res, name, '', { ...options, maxAge: 0 });
  }
}

// 使用例
// CookieManager.set(res, 'session', sessionId, { maxAge: 3600, sameSite: 'strict' });
// const cookies = CookieManager.parse(req.headers.cookie);
// CookieManager.delete(res, 'session');

Expressでのセッション管理

> Expressでセキュアなセッション管理を実装して。
> RedisをセッションストアにしてCSRF対策も入れて。

importに注意: connect-redis v7以降は完全にAPIが変わり、v6 までの const RedisStore = connectRedis(session) という高階関数呼び出しは廃止されました。v7 では RedisStore を default export として取り込み、そのまま new RedisStore({...}) でインスタンス化します。v8 では named exportRedisStore に変更されているので、使っているメジャーバージョンに合わせて import を書き分けてください。下記は v7 系(2025年時点で広く使われている安定版)の公式推奨形です。

import session from 'express-session';
import RedisStore from 'connect-redis'; // connect-redis v7: default import
// v8 を使う場合は: import { RedisStore } from 'connect-redis';
import { createClient } from 'redis';
import { csrfSync } from 'csrf-sync';

const redisClient = createClient({ url: process.env.REDIS_URL });
redisClient.on('error', (err) => console.error('Redis connection error:', err));
await redisClient.connect();

const sessionConfig: session.SessionOptions = {
  store: new RedisStore({ client: redisClient, prefix: 'sess:' }),
  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));

// CSRF対策(csrf-syncを使用)
const { csrfSynchronisedProtection, generateToken } = csrfSync({
  getTokenFromRequest: (req) => req.headers['x-csrf-token'] as string,
});
app.use(csrfSynchronisedProtection);

// CSRFトークンを返すエンドポイント
app.get('/api/csrf-token', (req, res) => {
  res.json({ token: generateToken(req) });
});

クライアント側の安全な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
無料プレゼント

無料PDF: Claude Code はじめてのチートシート

まずは無料PDFで基本コマンドと最初の使い方をまとめて確認してください。登録後はそのままテンプレート集や導入相談にも進めます。

スパムは送りません。登録情報は厳重に管理します。

Claude Codeを仕事で使える形にしませんか?

無料PDFで基礎を固めたあと、すぐ使えるテンプレート集で試し、必要なら業務自動化や導入相談まで進められます。

Masa

この記事を書いた人

Masa

現役DX室長|Claude Code でゼロから多言語AI技術メディア運営中。実務直結の自動化、AI開発相談・研修受付中。

PR

関連書籍・参考図書

この記事のテーマに関連する書籍を楽天ブックスで探せます。

※ 当サイトは楽天市場のアフィリエイトプログラムに参加しています。上記リンクから商品をご購入いただくと、運営者に紹介料が支払われる場合があります。