Trung BìnhBảo Mật iconBảo Mật

CORS là gì? Tại sao browser enforce same-origin policy?

Same-origin policy ngăn JavaScript từ một origin (scheme+host+port) đọc response từ origin khác — bảo vệ khỏi CSRF và data theft.

  • CORS cho phép server opt-in cho cross-origin requests qua response headers.
  • Simple requests (GET/POST với basic Content-Type) không cần preflight — browser gửi request và check response headers.
  • Preflight (OPTIONS request): cho non-simple requests (custom headers, PUT/DELETE, Content-Type: application/json) — browser gửi OPTIONS trước, server phải respond với allowed methods/headers trước khi browser gửi actual request.
  • Response headers: Access-Control-Allow-Origin: https://trusted.com (hoặc cho public APIs nhưng không thể dùng với credentials); Access-Control-Allow-Methods: GET, POST, PUT, DELETE; Access-Control-Allow-Headers: Content-Type, Authorization; Access-Control-Max-Age: 86400 (cache preflight 24h, giảm OPTIONS requests); Access-Control-Allow-Credentials: true (để gửi cookies/auth headers — phải specify exact origin, không dùng ).
  • Common mistakes: add CORS headers ở nginx nhưng app cũng trả CORS headers → duplicate headers → browser reject; thêm * nhưng cần credentials → không work; không handle OPTIONS method trong route → 405 error.
  • CORS chỉ restrict browser requests — Postman, curl, server-to-server không bị ảnh hưởng.
  • Credentials mode: fetch(url, { credentials: 'include' }) gửi cookies; cần server set Access-Control-Allow-Credentials: true và exact origin.

Xem toàn bộ Bảo Mật cùng filter theo level & chủ đề con.

Mở danh sách Bảo Mật