How to add CorsFilter along with Security-constraints in apache tomee?

543 views Asked by At

I have some RESTful web services developed in java using JAX-RS. I need to enable basic authentication on some of the methods. I am using apache tomee plume 7.0.2 as my application server.

I used security-constraint tag in web.xml to secure methods. Apache realm configurations is also set to DataSourceRealm.

Everything is fine till here.

I needed to add CORS headers to enable my js web ui use my services. So i added apache CorsFilter in web.xml. The problem is that for services that needs authentication, 401 response is returned and filters are not executed. So CORS headers are not added and my js client fails.

Is there a way to force executing filters after security constraints execution? How can I add custom headers in this scenario?

My web.xml configuration is:

<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,OPTIONS,PUT,DELETE</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials,X-Total-Count,WWW-Authenticate</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<security-constraint>
    <web-resource-collection>
        <web-resource-name>roastery creation</web-resource-name>
        <url-pattern>/roasteries</url-pattern>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>
</security-constraint>      

<login-config>
    <auth-method>BASIC</auth-method>
</login-config>

<security-role>
    <role-name>admin</role-name>
</security-role>
0

There are 0 answers