How To
Summary
This document describes how to configure Cross Origin Resource Sharing (CORS) headers for WebSphere Application Server, WebSphere Liberty, and IBM HTTP Server.
By default, pages running on a domain such as "origin.example.com" are not able to fetch pages from other domains such as "api.example.com" with JavaScript. These requests are blocked unless api.example.com returns special headers that direct the browser accessing origin.example.com that cross-origin requests are permitted.
This document assumes https://api.example.com/my-service provides an API intended to be called from sites running as part of the interactive site http://origin.example.com. Furthermore, http://api.example.com/my-service is powered by WebSphere and is the environment the reader has access to reconfigure.
It is only necessary to configure CORS in either the webserver or the application server
Steps
## 0. Enable the mod_headers module
# Find a line resembling "LoadModule headers_module modules/mod_headers.so" in httpd.conf
# If it's commented, remove the leading '#'. If it's entirely absent, append it to httpd.conf
## 1. Basic Example
# To allow any origin to access API's hosted behind this webserver
Header always set Access-Control-Allow-Origin "*"
# Override any value sent by the backend application.
Header onsuccess unset Access-Control-Allow-origin
# Avoid passing OPTIONS back to WebSphere in case WAS would redirect or return an error
# Note: This assumes the application does not use OPTIONS other than CORS pre-flight requests
SetEnvIfNoCase REQUEST_METHOD OPTIONS skipwas=1
## 2. Additional Examples (pick one)
# 2.1 To allow ONLY origin.example.com to access API's hosted behind this webserver
Header always set Access-Control-Allow-Origin "origin.example.com"
# 2.2 To allow any origin from a list of acceptable origins:
SetEnvIfNoCase Origin "https?://(origin1.example.com|origin2.example.com)(:\d+)?$" ACAO=$0
Header onsuccess unset Access-Control-Allow-origin env=ACAO
Header always set Access-Control-Allow-Origin "%{ACAO}e" env=ACAO
Header always append Vary "Origin"
SetEnvIfNoCase REQUEST_METHOD OPTIONS skipwas=1
# 2.3 To restrict the CORS configuration to a specific URL or context root, surround any of the above
# with the <Location> directive
<Location /my-service>
Header always set Access-Control-Allow-Origin "*"
# Or one of the more involved examples
</Location>
<cors domain="/my-service"
allowedOrigins="https://origin1.example.com,https://origin2.example.com"
allowedMethods="GET"
allowCredentials="true"
exposeHeaders="MyHeader"/>
Additional Information
Access to XMLHttpRequest at 'https://api.example.com/my-service' from origin 'https://origin.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Document Location
Worldwide
Was this topic helpful?
Document Information
Modified date:
03 October 2023
UID
ibm16348518