Tips & Tricks

如何Implement Cookie and Session Management:Claude Code 实战指南

学习如何implement cookie and session management:Claude Code 实战. 包含实用代码示例和分步指导。

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 可以生成。

// Client sideの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=/`;
  },
};

// Usage example:主题配置の保存
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 #session #security #TypeScript