Search This Blog

Monday, June 3, 2013

Example for enabling CORS support in Spring Rest Api 3.2

My last year's post "Enable CORS support in REST services with Spring 3.1" seems causing some confusion.  I decided to create an example to show how to enable CORS with Spring rest api.  The CorsFilter is same as before:


Below are 2 endpoints from EmployeeController.java:

The update method adds the header Access-Control-Allow-Origin with "*", but delete method doesn't.  Therefore, the update method is enabled with CORS, but delete isn't.  If delete endpoint is called, the following error will be shown in Chrome:

"cannot load http://localhost:8080/rest/employee/1. Origin http://127.0.0.1:8080 is not allowed by Access-Control-Allow-Origin."

However, the delete method is still invoked on the server side since the pre-flight request (OPTIONS)
allows DELETE method to be called.

The entire project can be downloaded from github.  Following README to test it.

My intention was to disable/enable CORS support in each individual method by setting "Access-Control-Allow-Origin", but it seems not working as expected:  Although the browser returns correct info, the method call is still invoked on the server side even Access-Control-Allow-Origin is not set.  If you are allowed to enable all endpoints with CORS support, the code can be simplified as below:

The only difference is that addHeader("Access-Control-Allow-Origin") is moved out the if check. And then the update method can be simplified as:

The code can be downloaded from github too.

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. As far as I know I id everything correctly, and the my web-app seems to run fine. The one thing I did not do was the Spring Configuration, but the web.xml was updated to add the filter. I also setup my controller as you described. However, my unit tests seems to be getting the correct status, but I am not getting any content back. Any help would be much appreciated. Thanks!

    ReplyDelete
    Replies
    1. did you get it work now? The spring configuration is to create the message converter and convert java object to json. If you still can't get it work, you may upload your code to github, so I can take a look.

      Delete
  3. I added your example to my application and works fine, it pass the filter for every single request, butI don't understand, why do you add this line to the filter. "response.addHeader("Access-Control-Allow-Origin", "*");" and then you have to add the same line to the header to allow it? Also I deleted the filter on my application and I just added the header on the controller and it worked fine as well. What does the filter do then?

    ReplyDelete
  4. What is the purpose of not having CORS on the response for DELETE, when it is invoked on the server side?

    ReplyDelete
  5. It is working fine, thanks for sharing.

    ReplyDelete