Adding CORS filter for KGS Web Services (WS)

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources.

Customers using our KGS Web Services can run into problems if they are attempting to access the KGS Web Services over their browser. In order to circumvent this problem, a mechanism knows as CORS Filter is needed to be activated on the server side to allow CORS. The following code needs to be added to the server’s web application web.xml. The following code applies to Tomcat 8.X/9.X;

<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.allowed.methods</param-name> <param-value>GET,POST,PUT,DELETE,HEAD,OPTIONS</param-value> </init-param> <init-param> <param-name>cors.allowed.headers</param-name> <param-value>Content-Type,X-Requested-With,Accept,Authorization,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> </init-param> <init-param> <param-name>cors.exposed.headers</param-name> <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern> /* </url-pattern> </filter-mapping>

 

The value against “cors.allowed.origins” should be adjusted according to customer’s need as the above code simply allows all resources to be accessed by users but with the above code, the user should atleast NOT get a CORS-related error/exception

This example allows every incoming request (from JS). It is highly recommended to allow only known servers by adatping the “cors.allowed.origins”