๐Ÿ”’ Security

Token-based Auth

Token-based Authentication

Authentication with tokens such as JWT. More scalable than sessions.

๐Ÿ“– Detailed Explanation

Token-based Authentication is a method in which the server does not store session state, and the client holds a token to authenticate. The server operates statelessly, which makes horizontal scaling easy, and it is well suited to microservice architectures and SPAs (Single Page Applications).

The most widely used token format is JWT (JSON Web Token). A JWT consists of three parts: Header (algorithm), Payload (claims), and Signature. The server signs the token with a secret key and verifies the signature on subsequent requests to detect token tampering. The token itself contains user information (ID, role, etc.), so authentication is possible without a separate DB lookup.

A typical token-based authentication flow: 1) The user logs in (ID/PW, OAuth, etc.), 2) The server issues an Access Token (+ Refresh Token), 3) The client stores the token (memory, localStorage, httpOnly cookie), 4) The client sends it in the Authorization: Bearer {token} header on API requests, 5) The server verifies the token and then processes the request.

It is common to set the Access Token with a short expiration time (5-15 minutes) and the Refresh Token with a long expiration time (several days to weeks). When the Access Token expires, a new Access Token is issued using the Refresh Token. Since the Refresh Token can also be stolen, Rotation (issuing a new one on each use) is recommended.

๐Ÿ’ป Code Example

// JWT ํ† ํฐ ๊ธฐ๋ฐ˜ ์ธ์ฆ ๊ตฌํ˜„ (Node.js + jsonwebtoken)
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';

const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET!;
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET!;

interface TokenPayload {
  userId: string;
  email: string;
  roles: string[];
}

// ํ† ํฐ ์ƒ์„ฑ
function generateTokens(payload: TokenPayload) {
  const accessToken = jwt.sign(payload, ACCESS_TOKEN_SECRET, {
    expiresIn: '15m',  // Access Token: 15๋ถ„
    issuer: 'myapp.com'
  });

  const refreshToken = jwt.sign(
    { userId: payload.userId },
    REFRESH_TOKEN_SECRET,
    { expiresIn: '7d' }  // Refresh Token: 7์ผ
  );

  return { accessToken, refreshToken };
}

// ๋กœ๊ทธ์ธ API
app.post('/api/auth/login', async (req, res) => {
  const { email, password } = req.body;

  // ์‚ฌ์šฉ์ž ์ธ์ฆ (DB ์กฐํšŒ)
  const user = await authenticateUser(email, password);
  if (!user) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  // ํ† ํฐ ๋ฐœ๊ธ‰
  const tokens = generateTokens({
    userId: user.id,
    email: user.email,
    roles: user.roles
  });

  // Refresh Token์€ httpOnly ์ฟ ํ‚ค๋กœ (XSS ๋ฐฉ์ง€)
  res.cookie('refreshToken', tokens.refreshToken, {
    httpOnly: true,
    secure: true,        // HTTPS๋งŒ
    sameSite: 'strict',  // CSRF ๋ฐฉ์ง€
    maxAge: 7 * 24 * 60 * 60 * 1000  // 7์ผ
  });

  // Access Token์€ ์‘๋‹ต body๋กœ
  res.json({ accessToken: tokens.accessToken });
});

// ์ธ์ฆ ๋ฏธ๋“ค์›จ์–ด
function authenticate(req: Request, 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 = jwt.verify(token, ACCESS_TOKEN_SECRET) as TokenPayload;
    req.user = payload;  // ์š”์ฒญ ๊ฐ์ฒด์— ์‚ฌ์šฉ์ž ์ •๋ณด ์ฒจ๋ถ€
    next();
  } catch (error) {
    if (error instanceof jwt.TokenExpiredError) {
      return res.status(401).json({ error: 'Token expired' });
    }
    return res.status(401).json({ error: 'Invalid token' });
  }
}

// ํ† ํฐ ๊ฐฑ์‹  API (Refresh Token Rotation)
app.post('/api/auth/refresh', async (req, res) => {
  const refreshToken = req.cookies.refreshToken;

  if (!refreshToken) {
    return res.status(401).json({ error: 'No refresh token' });
  }

  try {
    const payload = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET) as { userId: string };

    // DB์—์„œ ์‚ฌ์šฉ์ž ์ตœ์‹  ์ •๋ณด ์กฐํšŒ
    const user = await getUserById(payload.userId);

    // ์ƒˆ ํ† ํฐ ์Œ ๋ฐœ๊ธ‰ (Rotation)
    const tokens = generateTokens({
      userId: user.id,
      email: user.email,
      roles: user.roles
    });

    res.cookie('refreshToken', tokens.refreshToken, {
      httpOnly: true,
      secure: true,
      sameSite: 'strict',
      maxAge: 7 * 24 * 60 * 60 * 1000
    });

    res.json({ accessToken: tokens.accessToken });
  } catch {
    res.clearCookie('refreshToken');
    return res.status(401).json({ error: 'Invalid refresh token' });
  }
});

// ๋ณดํ˜ธ๋œ ๋ผ์šฐํŠธ
app.get('/api/users/me', authenticate, (req, res) => {
  res.json(req.user);
});

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

In authentication design:

"Session vs. token โ€” which is better?" - "For microservices, tokens are better. Each service can verify tokens independently, so it doesn't depend on the authentication server. However, since token invalidation is difficult, a combination of short expiration time + Refresh Token is essential."

In a technical interview:

"Where should I store the JWT?" - "Memory (a variable) is the safest place for the Access Token, but it disappears on refresh. localStorage is vulnerable to XSS, and httpOnly cookies are vulnerable to CSRF. In practice, a combination of the Access Token in memory and the Refresh Token in an httpOnly cookie is widely used."

In a security review:

"When a user changes their password, how do we invalidate their existing tokens?" - "Since a JWT cannot be invalidated by itself, we put a version (iat) in the token and store the last logout time in the DB. During verification, if iat < logout time, we reject it."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Cautions

๐Ÿ”— Related Terms

JWT OAuth 2.1 FIDO2 Session Cookie

๐Ÿ“š Learn More

๐Ÿ“„ JWT.io - Introduction to JSON Web Tokens ๐Ÿ“„ RFC 7519 - JWT Specification ๐Ÿ“„ Auth0 - Refresh Tokens Guide