CORS & Auth Basics AI-generated

CORS

CORS is on by default for every mock service (turn it off via Generate CORS Headers: Disabled under a Service's Fine-Tuning section, see Services - useful if you want to author the headers yourself, or deliberately test a client against a CORS-non-compliant backend). Response headers are only ever generated when the request itself carries an Origin header - non-browser calls (plain SOAP, server-to-server) are unaffected either way. Exact behavior depends on the request shape:

  • Simple requests (GET/POST/HEAD with no "unsafe" headers) get Access-Control-Allow-Origin: * back automatically - unrestricted.
  • Preflight requests - a browser's OPTIONS probe ahead of a non-simple method/header - get Access-Control-Allow-Methods and Access-Control-Allow-Headers echoing back exactly what the browser asked for, plus Access-Control-Allow-Origin: *.
  • Credentialed requests (carrying cookies) are handled differently, per the CORS spec's own requirement: Access-Control-Allow-Origin is set to the exact request Origin value (never *), and Access-Control-Allow-Credentials: true is added.

To override the automatically-generated headers for a specific reaction, set them explicitly in that reaction's Custom Headers section (see Reactions) - an explicit header there wins over the automatic one.

Basic HTTP Authentication

To mock an endpoint that requires HTTP Basic Auth, match on the presence/value of the Authorization header in a reaction's Match Options script (e.g. http.headers['Authorization']==null for the "missing credentials" case), and set that reaction's status to 401 with a WWW-Authenticate response header - ordinary reaction authoring, no special Basic Auth feature needed.

JWT-secured mocks

MockMotor has a native JWT object available to JavaScript reactions (not XQuery ones) for signing, decoding and verifying tokens, using the HS256, HS384 or HS512 algorithms - enough to build a small, fully self-contained mock login+authenticated-endpoint flow without any external auth service.

FunctionDoes
JWT.encode(header, payload, secret)Signs a new token. var token = JWT.encode(header, payload, "password123");
JWT.decode(token, secret)Parses a token to JSON without verifying it - adds an error field if it's malformed.
JWT.verify(token, secret)Decodes and validates - a bad signature or unsupported algorithm is a hard error (HTTP 500), not a soft failure.

Three fields are auto-populated from an incoming Authorization: Bearer <token> header, so you rarely need to parse it yourself: JWT.token (the raw token string, or null), JWT.header and JWT.payload (parsed objects, or {} if there's no token). Common uses: generate a token as part of a mocked login response; read JWT.payload fields to drive account selection/routing on a subsequent "authenticated" request; check standard claims like exp (expiration) or nbf (not-before) to simulate an expired- or not-yet-valid-token error.