Best Practices for Designing and Implementing JWT Authentication: Claude Code 활용 가이드
best practices for designing and implementing jwt authentication: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
JWT Authentication Fundamentals
JWT (JSON Web Token) is a token format that enables stateless authentication. With Claude Code, you can efficiently build a secure JWT authentication system.
Token Generation and Verification
import jwt from "jsonwebtoken";
import { z } from "zod";
const TokenPayloadSchema = z.object({
userId: z.string(),
email: z.string().email(),
role: z.enum(["admin", "user", "viewer"]),
});
type TokenPayload = z.infer<typeof TokenPayloadSchema>;
const JWT_CONFIG = {
accessSecret: process.env.JWT_ACCESS_SECRET!,
refreshSecret: process.env.JWT_REFRESH_SECRET!,
accessExpiresIn: "15m" as const,
refreshExpiresIn: "7d" as const,
};
function generateTokens(payload: TokenPayload) {
const accessToken = jwt.sign(payload, JWT_CONFIG.accessSecret, {
expiresIn: JWT_CONFIG.accessExpiresIn,
issuer: "my-app",
audience: "my-app-client",
});
const refreshToken = jwt.sign(
{ userId: payload.userId },
JWT_CONFIG.refreshSecret,
{
expiresIn: JWT_CONFIG.refreshExpiresIn,
issuer: "my-app",
}
);
return { accessToken, refreshToken };
}
function verifyAccessToken(token: string): TokenPayload {
const decoded = jwt.verify(token, JWT_CONFIG.accessSecret, {
issuer: "my-app",
audience: "my-app-client",
});
return TokenPayloadSchema.parse(decoded);
}
Authentication Middleware
import { Request, Response, NextFunction } from "express";
interface AuthenticatedRequest extends Request {
user?: TokenPayload;
}
function authMiddleware(
req: AuthenticatedRequest,
res: Response,
next: NextFunction
) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
return res.status(401).json({ error: "No token provided" });
}
const token = authHeader.slice(7);
try {
const payload = verifyAccessToken(token);
req.user = payload;
next();
} catch (error) {
if (error instanceof jwt.TokenExpiredError) {
return res.status(401).json({
error: "Token expired",
code: "TOKEN_EXPIRED",
});
}
return res.status(401).json({ error: "Invalid token" });
}
}
Refresh Token Rotation
For enhanced security, issue a new refresh token on each refresh.
import { Redis } from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
async function refreshAccessToken(refreshToken: string) {
// Check if the refresh token has been revoked
const isRevoked = await redis.get(`revoked:${refreshToken}`);
if (isRevoked) {
throw new Error("Refresh token has been revoked");
}
const decoded = jwt.verify(refreshToken, JWT_CONFIG.refreshSecret) as {
userId: string;
};
// Fetch user info
const user = await getUserById(decoded.userId);
if (!user) {
throw new Error("User not found");
}
// Revoke old refresh token
await redis.set(
`revoked:${refreshToken}`,
"1",
"EX",
7 * 24 * 60 * 60
);
// Generate new token pair
const payload: TokenPayload = {
userId: user.id,
email: user.email,
role: user.role,
};
return generateTokens(payload);
}
Login Endpoint
import bcrypt from "bcrypt";
app.post("/auth/login", async (req, res) => {
const { email, password } = req.body;
const user = await getUserByEmail(email);
if (!user) {
return res.status(401).json({ error: "Invalid credentials" });
}
const isValid = await bcrypt.compare(password, user.passwordHash);
if (!isValid) {
return res.status(401).json({ error: "Invalid credentials" });
}
const payload: TokenPayload = {
userId: user.id,
email: user.email,
role: user.role,
};
const tokens = generateTokens(payload);
// Set refresh token as HttpOnly Cookie
res.cookie("refreshToken", tokens.refreshToken, {
httpOnly: true,
secure: true,
sameSite: "strict",
maxAge: 7 * 24 * 60 * 60 * 1000,
});
res.json({ accessToken: tokens.accessToken });
});
Security Considerations
Key points to watch for in JWT authentication. For overall security design, also see OAuth Authentication Implementation.
| Risk | Mitigation |
|---|---|
| Token leakage | Short expiration + refresh tokens |
| XSS | HttpOnly Cookie + CSP |
| CSRF | SameSite attribute + CSRF tokens |
| Replay attacks | jti claim + blacklist |
Using with Claude Code
When implementing JWT authentication tailored to your existing codebase, instruct Claude Code as follows. For productivity tips, see 10 Tips to 3x Your Claude Code Productivity.
Implement JWT authentication.
- Access token: 15 minutes, Refresh token: 7 days
- Refresh token rotation support
- Redis-based token blacklist management
- Integrate with the existing user model
For detailed JWT specifications, see RFC 7519. For Claude Code usage, refer to the official documentation.
정리
JWT authentication offers the appeal of stateless design, but token management and security measures are critical. Implementing with Claude Code while understanding your entire project ensures a consistent authentication foundation.
무료 PDF: 5분 완성 Claude Code 치트시트
이메일 주소만 등록하시면 A4 한 장짜리 치트시트 PDF를 즉시 보내드립니다.
개인정보는 엄격하게 관리하며 스팸은 보내지 않습니다.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code 다국어 글을 매일 발행하기 전에 확인할 7가지
누락된 언어, 깨진 CTA, 반영되지 않은 배포를 막기 위해 다국어 Claude Code 글을 매일 발행하기 전에 확인할 체크리스트입니다.
Codex Automations란? 잠자는 동안 AI가 콘텐츠 운영을 처리하게 하는 방법
Codex Automations로 트래픽 분석, 주제 선정, 글 작성, CTA 개선, 배포까지 자동화하는 실전 가이드.
Claude Code × GCP Cloud Functions 완전 가이드 | 서버리스 함수 초고속 개발
Claude Code로 GCP Cloud Functions를 효율화. HTTP/Pub/Sub/Firestore 트리거 구현부터 로컬 테스트·배포 자동화까지, Masa의 실무 경험을 토대로 실제 코드로 해설.