JWT(JSON Web Token)の構造と安全な認証設計 (RFC 7519)
ステートレス認証、ヘッダー/ペイロード/署名の3分割構造、Base64URL、alg:none攻撃と検証の要点を解説。
Web Protocols & Security Architecture Research
JWT(JSON Web Token)の構造と安全な認証設計 (RFC 7519)
TL;DR — 設計・エンジニアリングの要点
- JWTはドットで区切られた3つの要素(ヘッダー、ペイロード、署名)で構成されます。
- データは単にBase64URLでエンコードされているだけであり、秘密鍵なしで誰でも中身を閲覧できます。
- デコードと検証は異なります。真正性の確認には秘密鍵を用いた署名の再計算が必須です。
- 重大な脆弱性である
alg: "none"攻撃を防ぐため、未署名トークンの受け入れを拒否する必要があります。 - ステートレスな特性上、即座の失効処理にはブラックリストや短い有効期限(exp)の設計が必要です。
中核概念とアーキテクチャ構造
Compact Serialization
StructureString format structured as `header.payload.signature` optimized for HTTP Authorization headers and URL parameters.
Registered Claims
ClaimsStandard predefined metadata fields (`iss` issuer, `sub` subject, `aud` audience, `exp` expiration, `iat` issued-at).
Symmetric Signing (HS256)
SigningBoth the identity provider and the API gateway share the identical secret key to sign and verify tokens.
Asymmetric Signing (RS256 / ES256)
PKIIdentity provider signs tokens with a private key; multiple microservices verify tokens using a public JWKS endpoint.
Stateless Verification
ScalabilityServices 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.
Header Construction
Declare the signing algorithm (e.g. HS256) and type.
{"alg": "HS256", "typ": "JWT"}Payload Construction
Populate registered claims (`exp`, `iat`) and domain-specific roles.
{"sub": "usr_9918", "role": "admin", "exp": 1799000000}Base64URL Encoding
Convert JSON bytes into URL-safe strings without padding (= characters replaced).
header_b64 = base64url(header);
payload_b64 = base64url(payload);Cryptographic Signature
Hash the concatenated header and payload with secret key.
sig = HMAC_SHA256(header_b64 + "." + payload_b64, secret);Token Assembly
Join all 3 components with periods to form the final compact token string.
jwt = header_b64 + "." + payload_b64 + "." + base64url(sig);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)
javascriptimport 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)
javascriptfunction 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)の適用理由と構成
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.
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)でよくある設計上の過ちと誤解
影響: 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.
影響: 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"`.
影響: 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.
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.
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
発生症状とエラーの兆候: TokenExpiredError: jwt expired
- `exp` timestamp in the past
- Server clock drift between issuer and verifier servers
JWT(JSON Web Token)の構造と安全な認証設計 (RFC 7519)に関するよくある質問
Q:Is the data inside a standard JWT encrypted?
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 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?
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.
おすすめの関連開発者ツール
100% クライアントサイド実行
用語集
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]IETFPrimary SpecificationRFC 7519 • Section 3 & 4Verified Primary SourceTechnical 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.”Source URI: https://datatracker.ietf.org/doc/html/rfc7519 - [2]IETFPrimary SpecificationRFC 7515 • Section 4 (Cryptographic Signatures)Verified Primary SourceTechnical Claim Supported:
Defines digital signatures and MAC algorithms (HS256, RS256, ES256) used to secure JWT integrity and verify token authorship.
Source URI: https://datatracker.ietf.org/doc/html/rfc7515 - [3]IETFAuthoritative Security StandardRFC 8725 • Security Considerations § 3Verified Primary SourceTechnical Claim Supported:
Mandates explicit algorithm validation on receiving servers, prohibiting the insecure "alg: none" algorithm and enforcing strict signature verification.
Source URI: https://datatracker.ietf.org/doc/html/rfc8725 - [4]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Token Storage & RevocationVerified Primary SourceTechnical Claim Supported:
Details token theft mitigation, recommending storage in secure HttpOnly cookies over localStorage and outlining token revocation strategies.
関連技術エコシステムと次の学習ステップ
おすすめの関連開発者ツール
関連技術解説記事
JWT vs Session-Based Authentication: Architecture & Performance
Compare database session lookups with stateless JWT verification across scalability and revocation.
Troubleshooting: JWT Works in Postman but Fails in Browser
Diagnose and remediate CORS header stripping, HttpOnly cookie constraints, and preflight authorization failures.
関連する技術Q&A
Can a JWT Be Decrypted by Anyone?
Answer: Yes, standard JSON Web Tokens (JWS) are signed, not encrypted. Anyone can decode and inspect the payload without the secret key.
Why Shouldn't You Store JWTs in LocalStorage?
Answer: Storing tokens in localStorage exposes them to instant exfiltration by any Cross-Site Scripting (XSS) vulnerability.
Can an Expired JWT Token Still Be Verified?
Answer: Yes, the cryptographic signature remains mathematically valid, but compliant libraries reject the token because exp is checked after signature verification.
開発者向け規格・仕様リファレンス
次のステップへ進む
JWT Interactive Tampering & Validation Lab
Put your theoretical understanding into practice by tampering with claims and testing signature rejection in the live sandbox.