Aller au contenu
uencoder

Implémenter CORS safely

CORS (Cross-Origin Resource Sharing) allows controlled cross-origin requests. Apprendre en configure origins, méthodes, headers, et identifiants safely.

  1. 1

    CORS allows a browser on one origin to request resources from another. The server responds with Access-Control-Allow-Origin (allowed origins), Access-Control-Allow-Methods (allowed HTTP methods), Access-Control-Allow-Headers (allowed request headers), and Access-Control-Allow-Credentials (whether cookies are allowed). Preflight requests (OPTIONS) check permissions before the actual request.

  2. 2
    Analyseur d'URL →

    Analyser the Origin header to validate the requesting origin. Compare against a whitelist of allowed origins. Never use Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true — this is invalid and browsers will reject it. Echo the specific origin back: Access-Control-Allow-Origin: https://example.com.

  3. 3
    Calculatrice de hash →

    For dynamic origin validation, hash the origin and compare against a set of allowed origin hashes. This avoids storing raw origins in configuration and allows O(1) lookup. Use SHA-256 for the hash. Alternatively, use a regex or prefix match for wildcard subdomains (*.example.com).

Questions fréquentes

Should I use CORS * (wildcard)?
Only for public APIs without credentials. With Access-Control-Allow-Origin: *, cookies are not sent (Access-Control-Allow-Credentials must be false), and all origins can access the API. For APIs with authentication or sensitive data, specify allowed origins explicitly. Never use * with credentials — browsers reject it.
What is a CORS preflight?
For "non-simple" requests (custom headers, methods other than GET/POST/HEAD, content type other than form/text), the browser sends an OPTIONS request first (preflight). The server responds with allowed methods, headers, and origin. If the preflight passes, the actual request is sent. Simple requests (GET with no custom headers) do not require preflight.

Workflows résolvant cette tâche

Outils associés