Tạo JSON Web Token với HMAC-SHA256
Công cụ JWT Generator của Tấn Phát Digital là giải pháp hoàn hảo cho developers cần tạo và test JSON Web Tokens (JWT) nhanh chóng trong quá trình phát triển và debug authentication systems. JWT là chuẩn mở (RFC 7519) được sử dụng rộng rãi trong modern web applications để truyền thông tin an toàn giữa các bên dưới dạng JSON object được ký số (digitally signed). Công cụ hỗ trợ HMAC-SHA256 algorithm - một trong những algorithms phổ biến nhất cho JWT signing. Giao diện trực quan với color-coded output giúp phân biệt rõ ràng 3 phần của JWT: Header (đỏ), Payload (tím), và Signature (cyan). Tự động thêm các standard claims với một click: iat (issued at), exp (expiration), nbf (not before), jti (JWT ID). Hiển thị thông tin token decoded bao gồm thời gian phát hành, thời gian hết hạn với color indicator (xanh nếu còn valid, đỏ nếu expired). Generate secret key ngẫu nhiên với UUID. Xử lý hoàn toàn trên trình duyệt, không gửi data lên server, đảm bảo bảo mật cho development workflow. Hoàn toàn miễn phí, không cần đăng ký tài khoản.
JSON Web Token (JWT) là chuẩn mở (RFC 7519) định nghĩa cách truyền thông tin an toàn giữa các bên dưới dạng JSON object. JWT được ký số (digitally signed) bằng secret key (HMAC) hoặc public/private key pair (RSA, ECDSA), đảm bảo tính toàn vẹn và xác thực của data. JWT được sử dụng rộng rãi trong: Authentication - sau khi user login, server trả về JWT, client gửi JWT trong mỗi request để authenticate. Authorization - JWT chứa user roles/permissions, server check để authorize access. Information Exchange - truyền data an toàn giữa services trong microservices architecture. Single Sign-On (SSO) - một JWT có thể dùng để authenticate across multiple domains. Developers cần JWT Generator để: Test authentication flows trong development. Debug JWT-related issues bằng cách tạo tokens với specific claims. Học và hiểu JWT structure và signing process. Tạo mock tokens cho unit tests và integration tests. Verify JWT implementation trong backend code.
JWT gồm 3 phần separated bởi dots (.): xxxxx.yyyyy.zzzzz. Header chứa metadata về token: 'alg' (algorithm dùng để sign, ví dụ HS256, RS256) và 'typ' (type, luôn là JWT). Header được Base64Url encoded. Payload chứa claims - statements về entity (thường là user) và additional data. Có 3 loại claims: Registered claims (predefined, recommended): iss (issuer), sub (subject), aud (audience), exp (expiration time), nbf (not before), iat (issued at), jti (JWT ID). Public claims: Defined by users, should be collision-resistant (use namespaces). Private claims: Custom claims agreed between parties. Payload cũng được Base64Url encoded. Signature được tạo bằng cách: HMACSHA256(base64UrlEncode(header) + '.' + base64UrlEncode(payload), secret). Signature verify rằng message không bị tampered và (với tokens signed bằng private key) verify sender identity.
iss (Issuer): Identifies principal that issued the JWT. Thường là URL của authentication server. Ví dụ: 'https://auth.example.com'. sub (Subject): Identifies the subject of the JWT - thường là user ID. Ví dụ: 'user123' hoặc UUID. aud (Audience): Identifies recipients that the JWT is intended for. Có thể là array. Ví dụ: 'https://api.example.com'. exp (Expiration Time): Unix timestamp sau đó JWT không còn valid. Ví dụ: 1735689600 (Jan 1, 2025). Quan trọng cho security - tokens nên có short expiration. nbf (Not Before): Unix timestamp trước đó JWT chưa valid. Useful cho scheduled access. iat (Issued At): Unix timestamp khi JWT được issued. Useful để determine age of token. jti (JWT ID): Unique identifier cho JWT. Useful để prevent replay attacks bằng cách track used tokens. Custom claims phổ biến: name, email, role, permissions, tenant_id, etc.
KHÔNG BAO GIỜ store sensitive data trong JWT payload vì nó chỉ được encoded (Base64), không encrypted - ai cũng có thể decode và đọc. Sử dụng HTTPS để truyền JWT, tránh man-in-the-middle attacks. Set expiration time ngắn (15 phút - 1 giờ) cho access tokens. Sử dụng refresh tokens với longer expiration để get new access tokens. Store JWT trong httpOnly cookies thay vì localStorage để prevent XSS attacks. Validate tất cả claims trên server: exp, nbf, iss, aud. Sử dụng strong secrets cho HMAC (ít nhất 256 bits). Consider RS256 (asymmetric) thay vì HS256 (symmetric) cho distributed systems. Implement token revocation mechanism (blacklist hoặc short expiration + refresh). Không trust client-side JWT validation - luôn validate trên server. Rotate secrets định kỳ. Log và monitor JWT-related activities.
Session-based: Server tạo session, store trong memory/database, gửi session ID trong cookie. Mỗi request, server lookup session. Pros: Easy revocation, server control. Cons: Stateful, scaling issues, CSRF vulnerable. JWT-based: Server tạo signed token, client store và gửi trong header. Server verify signature, không cần lookup. Pros: Stateless, scalable, cross-domain friendly, mobile-friendly. Cons: Harder revocation, larger payload, token theft risks. Khi nào dùng JWT: Microservices architecture cần stateless auth. Mobile apps và SPAs. Cross-domain authentication (SSO). APIs cho third-party consumers. Khi nào dùng Sessions: Traditional web apps với server-side rendering. Need immediate revocation capability. Simpler security model. Hybrid approach: Sử dụng JWT cho API authentication, sessions cho web app với sensitive operations.
Token expired (exp claim): Check server time sync, increase expiration, implement refresh token flow. Invalid signature: Verify secret key matches between generator và verifier. Check algorithm (HS256 vs RS256). Ensure no whitespace in secret. Token not yet valid (nbf claim): Check server time, adjust nbf claim. Malformed token: Ensure 3 parts separated by dots. Check Base64Url encoding (no padding =). Audience mismatch: Verify aud claim matches expected value. Algorithm confusion attack: Always specify expected algorithm in verification, không rely on header alg. Debugging tools: jwt.io để decode và verify tokens. Browser DevTools Network tab để inspect Authorization headers. Server logs để track validation errors. Công cụ này để generate test tokens với specific claims.
Công cụ xử lý hoàn toàn trên browser của bạn, không gửi bất kỳ data nào lên server. Tuy nhiên, KHÔNG NÊN dùng production secrets trên bất kỳ online tool nào (kể cả tool này) vì: Browser history có thể lưu lại. Browser extensions có thể access page content. Shared computers có thể expose data. Best practice: Chỉ dùng test/development secrets. Generate random secrets cho testing. Rotate secrets nếu accidentally exposed.
HS256 (HMAC-SHA256) là symmetric algorithm - dùng cùng một secret key để sign và verify. Simple, fast, phù hợp khi cả issuer và verifier đều trusted và có thể share secret. RS256 (RSA-SHA256) là asymmetric algorithm - dùng private key để sign, public key để verify. Phù hợp cho distributed systems khi verifiers không nên có signing capability. Tool này hỗ trợ HS256 vì nó phổ biến nhất và đơn giản hơn cho development/testing. Để test RS256, cần tools như jwt.io hoặc code-based generation.
JWT format: header.payload.signature. Header (phần 1, màu đỏ): Metadata về token - algorithm (alg) và type (typ). Base64Url encoded JSON. Payload (phần 2, màu tím): Claims/data - user info, permissions, expiration. Base64Url encoded JSON. Signature (phần 3, màu cyan): Cryptographic signature để verify integrity. Tạo bằng: HMAC(header + '.' + payload, secret). 3 phần design cho phép: Decode header/payload mà không cần secret (useful cho client). Verify integrity với signature. Compact format cho HTTP headers.
Đây là time-based claims quan trọng cho security: iat (Issued At): Unix timestamp khi token được tạo. Useful để track token age và detect old tokens. exp (Expiration): Unix timestamp sau đó token invalid. QUAN TRỌNG NHẤT - tokens không có exp có thể bị abuse indefinitely. Recommend: 15 phút - 1 giờ cho access tokens. nbf (Not Before): Unix timestamp trước đó token chưa valid. Useful cho scheduled access hoặc delayed activation. Server PHẢI validate exp và nbf. Tokens expired hoặc not-yet-valid phải bị reject.
Mỗi language có libraries để verify JWT: Node.js: jsonwebtoken library - jwt.verify(token, secret, options). Python: PyJWT library - jwt.decode(token, secret, algorithms=['HS256']). Java: jjwt library - Jwts.parser().setSigningKey(secret).parseClaimsJws(token). Go: golang-jwt library - jwt.Parse(token, keyFunc). PHP: firebase/php-jwt - JWT::decode($token, $key, ['HS256']). Verification steps: Decode header, check algorithm. Decode payload, extract claims. Verify signature với secret/public key. Validate exp, nbf, iss, aud claims. Return decoded payload nếu valid.
JWT vulnerabilities và mitigations: Token theft: Nếu attacker có token, họ có thể impersonate user. Mitigation: Short expiration, HTTPS only, httpOnly cookies, token binding. Algorithm confusion: Attacker change alg to 'none' hoặc switch RS256 to HS256. Mitigation: Always specify expected algorithm in verification code. Weak secrets: Brute-force attack on HMAC secrets. Mitigation: Use strong secrets (256+ bits), rotate regularly. Information disclosure: Payload readable by anyone. Mitigation: Never store sensitive data in JWT, use encryption (JWE) if needed. Replay attacks: Reuse stolen tokens. Mitigation: Short expiration, jti claim với server-side tracking, token binding.
CÓ, header và payload có thể decode bởi bất kỳ ai vì chúng chỉ được Base64Url encoded, KHÔNG encrypted. Đây là design intentional - JWT cho phép clients đọc claims mà không cần server roundtrip. Secret chỉ cần để: VERIFY signature (đảm bảo token không bị tampered). GENERATE valid signature khi tạo token. Implication: KHÔNG BAO GIỜ store sensitive data (passwords, credit cards, PII) trong JWT payload. Nếu cần encrypt payload, sử dụng JWE (JSON Web Encryption) thay vì JWS (JSON Web Signature).
Access token: Short-lived (15 phút - 1 giờ), dùng để access protected resources. Gửi trong mỗi API request. Refresh token: Long-lived (days - weeks), dùng để get new access token khi access token expired. Stored securely, chỉ gửi đến auth server. Tại sao cần cả hai: Security - nếu access token bị steal, damage limited do short expiration. UX - user không cần re-login thường xuyên nhờ refresh token. Revocation - có thể revoke refresh token để force re-authentication. Flow: Access token expired → Client gửi refresh token đến auth server → Server verify và issue new access token → Client continue với new token.
Chúng tôi không chỉ thiết kế website, mà còn giúp doanh nghiệp xây dựng thương hiệu số mạnh mẽ. Cung cấp dịch vụ thiết kế website trọn gói từ thiết kế đến tối ưu SEO. Hãy liên hệ ngay với Tấn Phát Digital để cùng tạo nên những giải pháp công nghệ đột phá, hiệu quả và bền vững cho doanh nghiệp của bạn tại Hồ Chí Minh.