POST request to Activiti REST API causes CORS issue when using Content-Type:application/json

拟墨画扇 提交于 2019-12-20 06:22:42

问题


I'm using AngularJS to consume Activit REST resources. All GET operations works as expected but, when I try to POST to /runtime/process-instances with Content-Type:application/json, it fails on the preflight. As you can see, there's no 'Access-Control-Allow-Origin' in the response header.

When I change the Content-Type to application/x-www-form-urlencoded;charset=utf-8, for example, the 'Access-Control-Allow-Origin' comes in the response header but as we know, my POST won't work as API expects it to have a content-type:application/json

How can I get around the issue?

Appreciate any input!


回答1:


Since Activiti 5.17, Activiti uses Spring Security to protect the REST-APIs. The Tomcat CORS-Filter only gets triggered if you send headers propagated in the allowed-headers field in the Tomcat CORS-Configuration. I did not succeed in triggering the CORS-filter on every request. Therefore, I did it this way:

  1. Write your own CORS-Filter

    public class CorsFilter extends OncePerRequestFilter {

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
    
            response.setHeader("Access-Control-Allow-Origin", "*");
            if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                response.setHeader("Access-Control-Allow-Headers", "accept, x-requested-with, Content-Type, Accept-Language, Accept-Encoding ,Origin, Access-Control-Request-Method ,Access-Control-Request-Headers, Last-Modified, Cookie, Referer");
                response.setHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin,Accept-Ranges,Content-Encoding,Content-Length,Content-Range");
                response.setHeader("Access-Control-Max-Age", "100");
            }
    
            filterChain.doFilter(request, response);
        }
    
    }
    
  2. Add the filter in the Spring Configuration in the activiti-rest-webapp2:

http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)

and .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

The options requests need to be passed without spring authentication because otherwise, the CORS preflight requests will fail.

If you do it this way, Activiti will add the Access-Control-Allow-Origin on every request you make.

Best regards Ben



来源:https://stackoverflow.com/questions/30132867/post-request-to-activiti-rest-api-causes-cors-issue-when-using-content-typeappl

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