Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling cross origin requests in Spring Data Rest

I have a web application that I am developing using Angular 2 and Spring Boot. I use the spring-boot-data-rest dependency to expose my repositories as HTTP endpoints.

During development, I run my backend spring boot project on a local tomcat that runs on port 8080. To develop the frontend, I use the angular-cli to serve my Angular 2 application on port 4200. My frontend running on 4200 needs to be able to hit the endpoints exposed on 8080, but that doesn't work because:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

If these were custom endpoints that I manually typed in a @RestController, I could simply add the @CrossOrigin annotation as such:

@RestController
public class MyController {
    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/whatever")
    public void whatever() {
        //whatever
    }
}

But I obviously cannot do this for my endpoints exposed by spring-boot-data-rest. So, how can I make those endpoints accessible from the http://localhost:4200 origin?

like image 729
Andrew Mairose Avatar asked Mar 07 '17 15:03

Andrew Mairose


1 Answers

I've used my custom CORS filter to make it work:

/**
 * Filter for enabling CORS support.
 */
@Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
                                    final FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addIntHeader("Access-Control-Max-Age", 10);
        filterChain.doFilter(request, response);
    }
}
like image 77
Yuriy Yunikov Avatar answered Oct 02 '22 21:10

Yuriy Yunikov