Let’s Talk About CORS
During my time working on the 48 hour startup I got caught in DCD (Developer Complusive Disorder). It was about CORS, and how I would handle requests to the API.
Solutions suggested *, but I felt that was an easy way out of the issue. Also, I wanted an API key to be restricted to a domain.
What is CORS
When requesting access to an API, a client system calls sends a packet of data to authenticate the request. If successful, the server responds with the data and all are happy.
Sometimes the API server will only accept requests from specific servers, thus increasing security (note: I don’t know how much it increases security, or how much it elevates the feeling of security).
Browsers have a security added into them to enforce Cross Origin Requests. It stops requests made from domains that are not the current website.
Domain A makes a request from data from Domain B. The Browser stops the request, as the User’s browser does not know what kind of data is being requested. It could be data that has a nefarious use in mind, or a hack in place to start infiltrating the User’s computer.
Thanks to browsers for implementing this.
Stopped. Now What?
While working on The 48 Hour Startup, I ran into a CORS issue, while trying to reach my goal. While setting up Antelope Studios to get data from my new service, I got the Cross Origin failure message, and at that point knew that I was not going to complete my goal.
I had read information about this previous, as I had encountered it on another project, and knew that I didn’t want to open the server up to a * type solution.
The easy way to bypass CORS on servers you have access to setup, is to allow * domains to cross domain request to you. Check out Enable CORS for more information on allowing requests.
Good Old Two Step
When making a CORS request two steps are taken into account. First the Browser will Preflight the request. A request with OPTIONS as the Request Method is set, if this is allowed it will continue with the request and all make the followup – real – request for data.
All of this checking is done within the headers of your request and response. The response headers must be good to accept the data. The main header being `Access-Control-Allow-Origin`, if it is `*` or the domain making the request (matches the Origin header in the HTTP request), then we are happy.
Because I wanted to implement a header system that had a little more trust than using `*`, I have to do some processing.
Using Symfony as a frame work means that I have access to the Request and Response to enable CORS functionality a little more strongly than adjusting my server to allow all Cross Origin requests.