Implement Security Filter API REST - CORS - Spring Framework 4.1

1

I am trying to implement security by URL to my REST API, I MEANT THAT PETITIONS FROM A SPECIFIC DOMAIN CAN ONLY BE CARRIED OUT, the solutions I find online tell me to use @CrossOrigin but the project in which I am working has the SPringFrameWork 4.1, and solutions with @CrossOrigin are available as of version 4.2 of SpringFrameWork.

I would greatly appreciate your help.

    
asked by Gonzalo Munive 24.05.2017 в 01:00
source

1 answer

1

In principle it should not be a very traumatic change from 4.1 to 4.2, but if for some reason you can not do it, you can always use a filter.

Put this in web.xml (I suggest that the url-pattern modify it to affect only the calls that interest you, for example / rest / *

<filter>
    <filter-name>GlobalFilter</filter-name>
    <filter-class>calabacin.controller.CorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>GlobalFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And then create the CorsFilter class so that it modifies the response in the cases specified in the url-pattern of the web.xml

public class GlobalFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // Establece aquí la cabecera que quieras
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Methods","GET,POST");
        resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter();
    }
}
    
answered by 24.05.2017 в 12:26