Cross-origin resource sharing (CORS) is a security mechanism that enables a web page from one domain to access resources from another domain.
In the context of REST APIs, CORS permits API calls from JavaScript on remote web pages. For example, this is necessary when using the "try it out" feature in interactive documentation hosted on API Hub for Design. In other words, for "try it out" requests to function properly, your API server must support CORS.
Note
CORS is used only when API Hub for Design proxy.
mode. It is not used when routing requests viaCORS is a server configuration. To support CORS on your API server, you need the following:
API responses must include CORS headers (see below).
API endpoints must support the OPTIONS method for CORS preflight requests. OPTIONS should not require authentication and must return a 200 response with the correct CORS headers.
Note
These requirements apply to all API endpoints, including OAuth endpoints.
CORS uses special HTTP headers to allow cross-domain requests. The "try it out" feature requires the following headers in API responses:
Access-Control-Allow-Origin: https://host.from.which.the.request.came
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: ResponseHeader1, ResponseHeader2, ...
Access-Control-Allow-Origin
Allows access to the resource from the specified request origin host. The value of this header must be set as follows:
If the request contains a non-empty
Origin
header (as in case of requests sent from a browser, such as "try it out" requests), return this origin along with theVary: Origin
header:Access-Control-Allow-Origin: https://host.from.which.the.request.came Vary: Origin
If the request does not have
Origin
, return the*
wildcard:Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
API Hub for Design sends "try it out" requests with client credentials (browser cookies, TLS client certificates, stored Authorization
entries). This header is required for such browser requests to work correctly.
Access-Control-Expose-Headers
A comma-separated list of response headers that the browser can access and display to the user. For example:
Access-Control-Expose-Headers: Content-Length, ETag, Link, X-RateLimit-Limit, X-RateLimit-Remaining
If this header is missing, "try it out" will only display simple response headers.
Access-Control-Allow-Headers
If your API uses OAuth 2.0, we recommend that the OPTIONS responses from the OAuth token endpoint (specified by tokenUrl
) include the Access-Control-Allow-Headers
response header containing the X-Requested-With
value. This will prevent the browser authentication dialog from appearing when incorrect cliend_id
or client_secret
is specified.
Access-Control-Allow-Headers: X-Requested-With, <other allowed request headers...>
For more information and to learn more about CORS, refer to the following topics: