Skip to content
youhoc
  • Pages
    • Home
    • Modern App Guidelines
    • Linux
      • Day 1: Linux Distributions & Navigation
      • Day 2: User Management
      • Day 3: File Permission & Ownership
      • Day 4: Package Management
      • Day 5: Services Management
    • Javascript
      • JS The Weird Part
        • Execution Context
        • Types & Operators
        • Objects & Functions
        • Error Handling & Strict Mode
        • Typescript, ES6, Tra
      • Modern JS
        • JS in the Browser
        • Data Storage JSON
        • Modern JS
        • Advanced Objects & Methods
        • Webpack & Babel
        • Async
      • jQuery
        • In-depth Analysis of jQuery
      • React-ready JS
        • Arrow Function
        • Template Literals
        • Logical AND, OR, Ternary, Nullish Operators
        • Destructuring & Rest Operator
        • Array Method
        • Immutability and Spread Operator
        • Promises, Async/Await, Callback
    • PHP
      • gruntJS
      • composer
      • MySQL
    • Docker
      • Container Basics
      • Container Networking
      • Container Image
      • Container Volume & Persistent Data
      • Dockerfile
      • Docker Compose
      • Docker Registry
    • Node.js
      • Installing & Exploring
      • Loading Modules
      • npm - Get Command Input
      • Web Server
        • Express Web Server
        • Template Engine & MVC
      • Authentication
      • 7. Databases
      • 8. Rest API
      • Errors
      • Sequelize
        • Sequelize Transactions: Đảm Bảo Tính Toàn Vẹn Dữ Liệu
        • 7 loại Data Types phổ biến Trong Sequelize
        • Phân Trang (Pagination) Trong Express.js Với Sequelize/MySQL
      • File Upload với Multer, Express.js
      • Hướng dẫn Cơ bản về Rest API
      • Server-Side Validation Với Express-Validator
      • icon picker
        Authentication Trong REST API Với JWT
    • ReactJS
      • React from Andrew
        • Summary from Next
        • 1. Basics
        • 2. React Components
        • 3. Webpack
        • 4. Styling with SCSS
        • 5. React Router
        • 6. React Hook
      • Modern React From The Beginning
        • Intro to JSX
        • Vite Build Tools
        • Basic Component Creation
        • Component State
        • Props & Component Composition
        • useState with Inputs & Form Submission
        • useEffect, useRef & Local Storage
        • Async / Await and Http Request in React
        • React Router: Declarative Mode
        • ContextAPI
        • React Router: Framework Mode
          • File-routing & HTML Layouts
          • Server-side Data Query
          • Links & Navigation
          • Loaders
    • Typescript
      • Type User vs UserProp
    • Payload CMS
    • Authentication

Authentication Trong REST API Với JWT

Tại sao REST API không dùng Session?

Session-based Authentication (Traditional Web Apps)

Token-based Authentication (REST API)

JWT (JSON Web Token) là gì?

JWT gồm 3 phần, ngăn cách bởi dấu chấm (.):
1. Header (màu đỏ):
2. Payload (màu xanh lá) - JSON Data:
3. Signature (màu xanh dương) - “Password” của JWT:
Tại sao Signature quan trọng?
Signature = “Chữ ký số” chỉ server tạo được (cần SECRET_KEY)

Cài đặt và sử dụng jsonwebtoken

1. Installation
jsonwebtoken là package phổ biến nhất cho JWT trong Node.js:
50+ million downloads/week
Maintained by Auth0
Industry standard
2. Setup Secret Key

Quy trình Đăng nhập (Login Flow)

1. User Login - Tạo Token

2. Client lưu Token

Nên lưu trong sessionCookie, an toàn hơn localStorage:

3. Verify Token trên

Để kiểm tra token có đúng không:
Copy token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Vào
Paste token vào ô “Encoded”
Paste secret key vào ô “Verify Signature”
Kiểm tra:
Decoded payload có đúng userId, email không?
“Signature Verified” có hiện không?

Sử dụng Token trong REST API Requests

1. Client gửi Token trong Header

2. Cấu hình CORS cho Authorization Header

3. Backend verify Token

4. Sử dụng middleware isAuth

Sử dụng Token để nhận diện User

1. Tạo Post với User ID

2. Chỉ cho phép user xóa post của chính họ

3. Admin có thể xóa bất kỳ post nào

Token Expiration Time Best Practices

Thời gian hết hạn phổ biến

Khuyến nghị:
Web Apps: 7 days
Mobile Apps: 30 days (user ít login lại)
Banking/Financial: 1-2 hours
Admin Panel: 12-24 hours

Refresh Token Pattern (Advanced)

Bảo Mật Token: Rủi ro và Cách Phòng Chống

Bất kỳ ai có được token đều có thể giả danh user đó hoàn toàn.
Token ≈ Username + Password kết hợp
Không cần nhập lại password
Không cần nhập captcha
Server tin tưởng 100%

Làm sao Token bị đánh cắp?

1. XSS (Cross-Site Scripting) Attack
Cách XSS xảy ra:
Comment section không sanitize input
User profile bio cho phép HTML
Third-party scripts bị compromise
2. Man-in-the-Middle (MITM) Attack
3. Phishing
4. Browser Extension độc hại

Cách Phòng Chống Token Theft

1. HttpOnly Cookies (An toàn hơn localStorage)
localStorage
HttpOnly Cookie
JavaScript đọc được?
✅ Có (XSS nguy hiểm!)
❌ Không (An toàn hơn)
Tự động gửi với requests?
❌ Phải thêm header
✅ Tự động
CSRF protection?
✅ An toàn
⚠️ Cần SameSite
Mobile Apps?
✅ Dễ dùng
❌ Khó hơn
There are no rows in this table
2. Short-lived Access Token + Refresh Token (đã nói ở trên)
Access token ngắn (15 phút) → Bị đánh cắp cũng ít thiệt hại
Refresh token dài (7 ngày) → Lưu httpOnly cookie (an toàn)
Nếu access token bị hack → 15 phút sau hết hạn
User không phải login lại liên tục
3. Token Rotation (Rotate Refresh Token)
Old refresh token chỉ dùng được 1 lần
Nếu hacker dùng old token → Server biết ngay có vấn đề
Có thể revoke tất cả tokens của user
4. Device/IP Tracking
5. User có thể quản lý devices/sessions
UI Example:
6. Sanitize User Input (Chống XSS)
7. Content Security Policy (CSP)
Câu trả lời câu hỏi của bạn:
Đúng - Ai có token = Giả danh được user
Đúng - User phải tự quản lý token trên mỗi device
Giải pháp - HttpOnly cookies + Short expiration + Device management + Security alerts
Best practice đơn giản nhất:
Access Token: 15 phút (localStorage OK)
Refresh Token: 7 ngày (httpOnly cookie)
User có thể xem và revoke sessions
HTTPS bắt buộc trong production

Best Practices JWT trong REST API

1. Luôn dùng HTTPS trong Production

2. Secret Key phải mạnh và bảo mật

3. Không lưu sensitive data trong token

4. Validate token mỗi request

5. Handle token expiration gracefully

6. Logout: Invalidate token

7. Rate limiting cho login endpoint

8. Logging và monitoring

9. Multi-device support (Mỗi device 1 token)

10. Environment-specific configurations

Complete Example: Full Auth Flow

Tóm tắt
Khái niệm
Giải thích
Stateless
Server không lưu session, mọi thông tin trong token
JWT
JSON Web Token = Header + Payload + Signature
Signature
“Chữ ký số” chỉ server tạo được (cần SECRET_KEY)
Bearer Token
Format: Authorization: Bearer <token>
isAuth middleware
Verify token trước khi vào protected routes
req.userId
Sau verify, biết user nào đang request
Expiration
7 days (web), 30 days (mobile), 1h (banking)
Best practices
HTTPS, strong secret, validate mọi request, handle expiration
There are no rows in this table
JWT là chuẩn industry cho authentication trong REST APIs - đơn giản, secure, và scalable!
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.