How to 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
Related Posts
Tips & Tricks
Tips & Tricks
Claude Code 생산성을 3배로 높이는 10가지 팁
Claude Code를 더 효과적으로 활용하는 10가지 실전 팁을 공개합니다. 프롬프트 전략부터 워크플로 단축키까지, 오늘부터 바로 적용해 보세요.
Tips & Tricks
Tips & Tricks
Canvas/WebGL Optimization: Claude Code 활용 가이드
canvas/webgl optimization: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
Tips & Tricks
Tips & Tricks
Markdown Implementation: Claude Code 활용 가이드
markdown implementation: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.