Tuesday, February 25, 2014

Avoiding CORS security issues

CORS is security policy, according which a page could not be iframe-d from page from another site.

ajax requests are implemented via iframe, so if we want to do ajax requests to another site, we encounter CORS error.

How to enable this?

Solution is to tell server to allow the page/JSON/webservice to be iframed. This is done this way:
    public String getUserById(@PathVariable("id") Long id, HttpServletResponse httpResponse) throws JsonProcessingException {
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        // do real work

    }

Access-Control-Allow-Origin is the header that allows this. Check wikipedia for other solutions.

solved: Spring + Hibernate used with JPA and EntityManager => HibernateException: collection is not associated with any session

When I started using lazy loading in Spring + Hibernate project, I encounter this error.

What does NOT solve my issue:
  • @Transactional annotation
  • OpenSessionInViewInterceptor


The error message was:

HTTP ERROR 500

Problem accessing /user/1. Reason:
    Server Error

Caused by:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: collection is not associated with any session
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)


Solution for Spring with JPA approach and EntityManager, is to use OpenEntityManagerInViewFilter. Register it in web.xml this way: