jersey cross domain request

1.4k Views Asked by At

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.

3

There are 3 best solutions below

0
On

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>
0
On

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
0
On

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/