Reading:
Tomcat CORS Configuration

Tomcat CORS Configuration

Metamug
Tomcat CORS Configuration

Introduction

This article requires basic understanding of Cross Origin Resource Sharing (Cors) and Apache Tomcat configurations

CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.

Note that you need Tomcat 7.0.41 or higher.

CorsFilter Features

Apache tomcat already comes with CorsFilter which is a Filter implementation. So we don't need to write our own filter. CorsFilter configuration allows us to configure the following,

  • origins
  • methods
  • headers
  • credentials

Adding CORS filter in web.xml

Comma seperated values must be added for each of the init params.

<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>http://localhost:8080,https://example.com,https://app.example.com</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,DELETE,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,Authorization,Accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Content-Length,Connection</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Authorization,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,Content-Type,Content-Length,Content-Encoding,Connection</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


Icon For Arrow-up
Comments

Post a comment