0

I have a theoretical doubt on CORS implementation.

A way to enable cross-origin requests is to set a specific Header on the response:

private void setAccessControlHeaders(HttpServletResponse resp) {
  resp.setHeader("Access-Control-Allow-Origin", "http://www.allowed.domain.com");
  resp.setHeader("Access-Control-Allow-Methods", "POST");
}

My question is: if I set the header in the response (which is at the end of the request-response chain), it means the request I receive is already processed, side effects are caused, and then the program decides if the response must be sent back or not, based on the presence of this header in the response.

For example:

public class MyServlet extends HttpServlet {

    //...        

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws Exception{

        Order order = (Order) parseBodyRequest(req);
        orderRepository.save(order);                 //if I check the allowed domains later, I can get serious side effects!

        resp.setHeader("Access-Control-Allow-Origin","http://www.allowed.domain.com");
        resp.getWriter().println("Order n."+ order.getId()+ "has been saved successfully!");
    }
}

In the example above, the order is parsed and saved into the database before even checking if the domain from which the request comes is allowed or not.

This thing seems absurd, so how does it work in reality?

Alex Mawashi
  • 1,686
  • 2
  • 21
  • 42
  • 1
    https://stackoverflow.com/questions/38375124/what-is-the-reason-behind-using-option-request-before-post-on-cors-requests – Barry Pollard Sep 21 '19 at 07:54

1 Answers1

2

Try this article: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

In short: For requests that are able to alter user data, CORS specifies a preflight request that asks the destination server whether it would accept a request with a given method and set of headers. (eg POST and Content-type) without actually sending the request. The browser implements this transparently.

peeebeee
  • 2,273
  • 6
  • 18
  • 24
  • So, for example, with a POST request the client (browser, microservice, desktop app) always makes a pre-request? Or is it an enable/disable option for the browsers? – Alex Mawashi Sep 20 '19 at 14:34
  • 1
    It's part of CORS, so the browser has to implement it - I guess you might be able to turn it off but then it's not CORS. – peeebeee Sep 20 '19 at 14:38