100% 브라우저 메모리 연산 • 서버 로그 수집 제로 • 즉각적인 실행
Curious Techie개발자 툴박스
JWT8분 소요•한국어 Edition100% 브라우저 메모리 실행

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)

무상태(Stateless) 인증, 헤더/페이로드/서명 3단 구조, Base64URL 인코딩 및 디코딩과 검증의 차이점 해설.

CT
Curious-Techie Engineering Team검증된 작성자

Web Protocols & Security Architecture Research

발행일:
•
수정일:
•8분 소요
공식 기술 규격:RFC 7519(IETF)
검토자: Curious-Techie Architecture Peer Review Group
핵심 질문 • 즉시 기술 답변

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)

TL;DR — 핵심 엔지니어링 요약

  • JWT는 마침표(.)로 구분되는 세 부분, 즉 헤더(Header), 페이로드(Payload), 서명(Signature)으로 이루어집니다.
  • 데이터는 단순 Base64URL로 인코딩되어 있어 비밀키 없이도 누구나 내용을 확인할 수 있습니다.
  • 토큰을 디코딩하는 것과 검증하는 것은 완전히 다릅니다. 신뢰성을 위해 반드시 암호학적 서명을 재계산해야 합니다.
  • 취약한 백엔드가 서명 없는 토큰을 허용할 때 발생하는 alg: "none" 공격을 차단해야 합니다.
  • 서버 저장소가 없는 무상태 특성으로 인해 즉각적인 토큰 무효화에는 차단 목록이나 짧은 만료 시간이 필요합니다.
// 기본 개념

핵심 개념 및 아키텍처 구조

Compact Serialization

Structure

String format structured as `header.payload.signature` optimized for HTTP Authorization headers and URL parameters.

Registered Claims

Claims

Standard predefined metadata fields (`iss` issuer, `sub` subject, `aud` audience, `exp` expiration, `iat` issued-at).

Symmetric Signing (HS256)

Signing

Both the identity provider and the API gateway share the identical secret key to sign and verify tokens.

Asymmetric Signing (RS256 / ES256)

PKI

Identity provider signs tokens with a private key; multiple microservices verify tokens using a public JWKS endpoint.

Stateless Verification

Scalability

Services verify authorization cryptographically using keys in memory without database lookups.

실행 흐름 • 동작 시퀀스

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)의 동작 원리와 메커니즘

핵심 요약 답변:

When an authentication server validates a user’s credentials, it constructs a JSON payload containing user identity and authorization claims. It serializes the header and payload as Base64URL strings, concatenates them with a dot, and feeds the resulting string into a cryptographic signing function along with a private secret or key. The resulting signature is appended. Downstream services verify the token by recomputing or validating the signature against the received header and payload.

1

Header Construction

Declare the signing algorithm (e.g. HS256) and type.

{"alg": "HS256", "typ": "JWT"}
2

Payload Construction

Populate registered claims (`exp`, `iat`) and domain-specific roles.

{"sub": "usr_9918", "role": "admin", "exp": 1799000000}
3

Base64URL Encoding

Convert JSON bytes into URL-safe strings without padding (= characters replaced).

header_b64 = base64url(header);
payload_b64 = base64url(payload);
4

Cryptographic Signature

Hash the concatenated header and payload with secret key.

sig = HMAC_SHA256(header_b64 + "." + payload_b64, secret);
5

Token Assembly

Join all 3 components with periods to form the final compact token string.

jwt = header_b64 + "." + payload_b64 + "." + base64url(sig);
6

Bearer Token Transmission

Client includes token in Authorization header for subsequent API requests.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
기술 예제 • 실전 구현

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)의 실무 구현 및 적용 방법

Verifying a JWT Signature in Node.js (Crypto Native API)

javascript
import crypto from "crypto";

function verifyHS256(jwt, secret) {
  const [headerB64, payloadB64, signatureB64] = jwt.split(".");
  if (!headerB64 || !payloadB64 || !signatureB64) return false;

  const data = `${headerB64}.${payloadB64}`;
  const expectedSig = crypto
    .createHmac("sha256", secret)
    .update(data)
    .digest("base64url");

  // Constant-time comparison to prevent timing attacks
  return crypto.timingSafeEqual(
    Buffer.from(signatureB64),
    Buffer.from(expectedSig)
  );
}

엔지니어링 상세 정보: Native cryptographic verification using timing-safe buffer comparison to prevent side-channel timing attacks.

Decoding JWT Claims in Browser JavaScript (Client-Side Safe)

javascript
function parseJwtPayload(token) {
  const base64Url = token.split(".")[1];
  const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
  const jsonPayload = decodeURIComponent(
    atob(base64)
      .split("")
      .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
      .join("")
  );
  return JSON.parse(jsonPayload);
}

엔지니어링 상세 정보: Pure client-side parsing without third-party dependencies, properly handling Unicode UTF-8 character boundaries.

프로덕션 아키텍처 • 실사례 연구

운영 환경에서 JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)을 사용하는 이유와 구성

Decentralized Microservices Architecture

API gateway receives user login, issues RS256 token; 50 downstream microservices independently verify claims.

Services download the gateway’s public JWKS (`/.well-known/jwks.json`) once and cache it, avoiding auth server query bottlenecks.

Mobile App API Authorization

iOS and Android native applications maintaining offline access tokens with refresh rotation.

Access token valid for 15 minutes; refresh token stored in OS Keychain used to request fresh JWTs silently.

안티패턴 및 주의사항

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519) 구현 시 자주 발생하는 실수와 오해

안티패턴: Treating JWT payload claims as encrypted private data

영향도: Sensitive passwords, SSNs, or PII stored in payload are visible to anyone who intercepts the token.

권장 해결책: Remember that standard JWS tokens are signed, not encrypted. Use JWE (RFC 7516) or store only non-sensitive IDs in claims.

안티패턴: Failing to validate the `alg` header (The "alg: none" Vulnerability)

영향도: Attackers modify the header to `"alg": "none"`, strip the signature, and forge arbitrary admin permissions.

권장 해결책: Hardcode expected verification algorithms on the server (e.g. `algorithms: ["HS256"]`) and reject any `"alg": "none"`.

안티패턴: Failing to validate expiration (`exp`) claim timestamps

영향도: Stolen tokens remain valid perpetually, enabling indefinite account takeovers.

권장 해결책: Always mandate strict expiration checks against current UTC timestamp (`exp < Math.floor(Date.now() / 1000)`).

위협 모델링 • 공격 벡터

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)의 보안 영향 및 취약점 분석

Algorithm Confusion Attack (HMAC vs RSA Key Confusion)

CVE-2015-9235 (Algorithm Confusion)

취약점: Server expects RS256 with public key; attacker signs token using HMAC-SHA256 with the server’s public key as the symmetric secret.

완화 및 방어 전략: Explicitly enforce the expected algorithm; never allow client header `alg` to dictate whether verification uses a public or symmetric key.

Weak Symmetric Secrets & Brute-Forcing

CWE-326 Inadequate Encryption Strength

취약점: Using a weak HMAC secret (e.g. "secret123") allows attackers to brute-force the key offline using Hashcat at billions of guesses per second.

완화 및 방어 전략: Generate cryptographically random secrets with at least 256 bits of entropy (32 random bytes from `/dev/urandom`).
진단 워크플로 • 근본 원인 해결

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519) 오류 진단 및 트러블슈팅 가이드

발생 증상 및 오류 징후: JsonWebTokenError: invalid signature

근본 원인 기술 분석:
  • Secret key mismatch between issuer and validator
  • Payload mutated in transit
  • Trailing whitespace or padding corrupted Base64URL string
프로덕션 검증 해결책: Inspect token in Curious-Techie JWT Decoder; verify environment variable `JWT_SECRET` matches across both services.

발생 증상 및 오류 징후: TokenExpiredError: jwt expired

근본 원인 기술 분석:
  • `exp` timestamp in the past
  • Server clock drift between issuer and verifier servers
프로덕션 검증 해결책: Configure small clock tolerance (`clockTolerance: 10` seconds) in verifier library; ensure NTP synchronization on servers.
기술 지식베이스 • 즉시 답변

JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519)에 대한 자주 묻는 질문

Q:Is the data inside a standard JWT encrypted?

핵심 요약 답변:No. Standard JWTs (RFC 7519 JSON Web Signatures) are only signed and Base64URL-encoded, not encrypted. Anyone who intercepts the token can decode and view all payload claims in plaintext.

A signature guarantees integrity (that data was not tampered with) and authenticity (who created it), but provides zero confidentiality. If confidential payload data is required, JSON Web Encryption (JWE, RFC 7516) must be used.

Q:What is the difference between HS256 and RS256?

핵심 요약 답변:HS256 is symmetric (both signer and verifier share one secret key). RS256 is asymmetric (the identity provider signs with a private key, and anyone can verify using the public key).

HS256 is ideal for monolithic apps where only one backend needs to verify the token. RS256 is preferred in microservices because worker services only need the public key and cannot forge their own tokens.

Q:How do you revoke a JWT before it expires?

핵심 요약 답변:Because JWTs are stateless, instant revocation requires checking a centralized blacklist (e.g. in Redis) or keeping token lifetimes very short (e.g. 10 minutes) and revoking the refresh token.

Pure statelessness means the token is self-contained. To revoke immediately, architectures typically store a `jti` (JWT ID) blacklist in a low-latency Redis cache or invalidate the user’s token generation counter.

섹션 12 • 대화형 실습 유틸리티

추천 관련 개발자 도구

100% 브라우저 메모리 실행

Companion Interactive Tool100% Client-Side Execution

Test & Verify with JWT Decoder

Decode and inspect JWT headers, payloads, and signatures securely.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with JWT Security Inspector

Audit JWT vulnerabilities: none algorithm, weak signing, and claim flaws.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with Base64 Encoder / Decoder

Encode and decode Base64 strings and UTF-8 text client-side.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with Cryptographic Hash Generator

Generate SHA-256, SHA-384, SHA-512, SHA-1, and MD5 hashes locally.

용어사전

JWT
JSON Web Token: Compact URL-safe means of representing claims to be transferred between two parties.
Claim
A piece of information asserted about a subject, represented as a key-value pair in the JSON payload.
Base64URL
URL-safe Base64 encoding where + is replaced with -, / is replaced with _, and padding = is omitted.
JWKS
JSON Web Key Set: A JSON data structure representing a set of public cryptographic keys.
Authoritative Sourcing & Verification

References & Primary Sources

Every source below directly substantiates technical statements and protocol behaviors explained in JWT란 무엇인가? JSON Web Token 아키텍처 (RFC 7519). Curious-Techie prioritizes official Internet standards (IETF RFCs, W3C Recommendations, WHATWG specifications) and established security bodies (OWASP, NIST). Zero sponsored or secondary links.

  1. [1]IETFPrimary SpecificationRFC 7519 • Section 3 & 4
    Verified Primary Source
    Technical Claim Supported:

    Defines the compact, URL-safe format of JSON Web Tokens consisting of three Base64URL segments (Header, Payload, Signature) and registered claims (iss, sub, aud, exp, nbf, iat, jti).

    “A JWT is represented as the concatenation of the Encoded JWT Header, the Encoded JWT Claims Set, and the Encoded JWT Signature or Encoded JWT Encryption Data, with the parts being separated by period ('.') characters.”
  2. [2]IETFPrimary SpecificationRFC 7515 • Section 4 (Cryptographic Signatures)
    Verified Primary Source
    Technical Claim Supported:

    Defines digital signatures and MAC algorithms (HS256, RS256, ES256) used to secure JWT integrity and verify token authorship.

  3. [3]IETFAuthoritative Security StandardRFC 8725 • Security Considerations § 3
    Verified Primary Source
    Technical Claim Supported:

    Mandates explicit algorithm validation on receiving servers, prohibiting the insecure "alg: none" algorithm and enforcing strict signature verification.

  4. [4]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Token Storage & Revocation
    Verified Primary Source
    Technical Claim Supported:

    Details token theft mitigation, recommending storage in secure HttpOnly cookies over localStorage and outlining token revocation strategies.