Lesson 14 / 25

HTTPS, CORS & Input Validation

Secure an API with HTTPS everywhere, correct CORS rules and strict server-side input validation.

HTTPS everywhere

Serve every API over HTTPS. Tokens, API keys and personal data in headers or bodies are readable on the network without it. Redirect HTTP to HTTPS and send Strict-Transport-Security so browsers never downgrade.

CORS in practice

Browsers block cross-origin calls unless the server opts in. Allow only the origins you trust, never * together with credentials.

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Vary: Origin

Validate on the server

Never trust client input. Validate type, length, range and format against a schema, reject bad requests with 400 or 422, and use parameterised queries to prevent injection.

Quick check

Quick check: Which CORS setting is unsafe with credentialed requests?

  • Allow-Origin: *
  • Allow-Origin: a trusted origin
  • Vary: Origin
  • Allow-Headers: Authorization
Answer

Allow-Origin: * — A wildcard origin lets any site call your API with a user's credentials.