jersey cross domain request

亡梦爱人 提交于 2020-01-06 06:53:30

问题


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:

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.


回答1:


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>



回答2:


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



回答3:


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/



来源:https://stackoverflow.com/questions/30974730/jersey-cross-domain-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!