CORS Requirements for "Try It Out"
Cross-origin resource sharing (CORS) is a security mechanism that allows a web page from one domain to access resources from another domain.
In the context of REST APIs, CORS allows making API calls from JavaScript on remote web pages, such as from the interactive documentation hosted on API Hub for Portal. In other words, your API server must support CORS in order for "try it out" requests to work.
Note
CORS is used only in the Routing requests via browser mode. CORS is not used when routing requests via API Hub for Portal proxy.
Enable CORS
CORS 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 must not require authentication and should return a 200 response with the proper CORS headers.
These requirements apply to all API endpoints, including OAuth endpoints.
Required CORS headers
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 Portal sends "try it out" requests with client credentials (browser cookies, TLS client certificates, stored Authorization
entries). This header is required for such requests to work properly from a browser.
Access-Control-Expose-Headers
A comma-separated list of response headers that the browser is allowed to 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...>
Further reading
Here are some helpful resources to learn more about CORS:
CORS guide in Mozilla documentation