Thursday, 6 July 2017

Enable CROS at Spring


I developed a group Rest API and deployed at Heroku; however, it cannot be invoked from another domain for violating the same origin principle. It is a kind of security setup.

So I tried to use Spring @CrossOrigin to enable at rest controller or method level. However, it doesn't work well.

Therefore, I switched to a classical way, where I created a filter to modify the response header in order to enable CORS. It works well now.

In the Spring boot, a filer can be annotated as a component, thus it will be automatically picked up as the moment Spring context is initialized.

The reason because:

Spring MVC provides fine-grained support for CORS configuration through annotations on controllers. However, when used with Spring Security, we advise relying on the built-in CorsFilter that must be ordered ahead of Spring Security’s chain of filters.


What is CORS

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.

The following diagram illustrates the Spring MVC's working flow,i.e. how a request received from the client is dispatched internally to controllers and send back to the client in response.

There is one way where we intercept all responses and modify their headers to enable CORS.





Cross-Origin Resource Sharing (CORS)

Spirng MVC 4 CORS Setup

Enable CORS in Spring Boot (in a filter)

Understanding CORS


Spring CORS controller annotation not working

Spring @CrossOrigin does not work with DELETE method

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...