0

I am using jersey 2.18 for developing rest api. (using tomcat container)

I want to allow access to clients from other domain.

So I am trying below code to allow cross domain requests.

Filter

public class MyCorsFilter implements Filter {

    public MyCorsFilter() { }

    public void init(FilterConfig fConfig) throws ServletException { }

    public void destroy() { }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException  {
      ((HttpServletResponse)response).addHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(request, response);
    }
}

web.xml

<filter>
    <filter-name>MyCorsFilter</filter-name>
    <filter-class>MyCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyCorsFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

Above code works fine until I add HTTP basic authentication.

When I add basic authentication I am getting following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

When checked headers using developer tools I found following:

enter image description here

Please note that the error is while executing OPTIONS method. (I am using GET method)

Any suggestion on how to add allow CORS with basic HTTP authentication will be appreciated.

Bhushan
  • 6,151
  • 13
  • 58
  • 91

3 Answers3

0

You can have Catalina CORS filter configurations in your web.xml as below -

    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Puneet Pandey
  • 960
  • 2
  • 14
  • 28
0

Puneet is right.

Take note you will probably have to setup some parameters, namely :

  • cors.allowed.origins
  • cors.allowed.methods
  • cors.allowed.headers
  • cors.exposed.headers
Filip
  • 906
  • 3
  • 11
  • 33
0

Actually browser makes preflight request before your actuall request with http request method "options" . so you have to send 200 OK to this request and allow cross domain header like

 httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
    httpResponse.setHeader("Access-Control-Max-Age", "3600");
    httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type");
    if(httpRequest.getMethod().equals("OPTIONS")){
        httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }

More information you can find at http://enable-cors-org/

Prabjot Singh
  • 4,491
  • 8
  • 31
  • 51