aneta_bielska [:blog]

CORS: a way to deal with external API
#cors #same-origin-policy

While working on my application I decided to make some serious changes. One of them is splitting backend and frontend.

Splitting frontend and backend give us couple of advantages:

I picked only three I find the most important. In this post I am going to write about a way of manipulating and getting data from external api.

A thing that is on the way is same origin policy.

The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. It is a critical security mechanism for isolating potentially malicious documents.

Check those examples:

Compared URL
(http://www.example.com/dir/page.html)
Outcome Reason
http://www.example.com/dir/page2.html Success Same protocol, host and port
http://www.example.com/dir2/other.html Success Same protocol, host and port
http://username:password@www.example.com/dir2/other.html Success Same protocol, host and port
http://www.example.com:81/dir/other.html Failure Same protocol and host but different port
https://www.example.com/dir/other.html Failure Different protocol
http://en.example.com/dir/other.html Failure Different host
http://example.com/dir/other.html Failure Different host (exact match required)
http://v2.www.example.com/dir/other.html Failure Different host (exact match required)
http://www.example.com:80/dir/other.html Depends Port explicit. Depends on implementation in browser.

The solution: 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 resource originated.

Allows server to specify who/what can access endpint directly, under what condition and what headers will be returned. Cors allows to use plain JSON, ALL HTTP Verbs: GET, POST, PUT etc. It requires configuration on api server side.

On client side:

$.ajax({
  dataType: "json",
  ...
});

Most work is done between browser and server, via http headers.

Browser passes origin header to server. origin: www.example.com. Server responds (header) saying what is allowed: Access-Control-Allow-Origin: www.example.com, then: direct http GET/POST…(as allowed by Access headers).

You may also enjoy:


#servers (1) #hosting (1) #sinatra (2) #assets (1) #sprockets (1) #react-js (1) #data-mapper (1) #ROM (1) #sequel (1) #ORM (1) #pg (1) #sqlite3 (1) #postgresql (1) #ruby (4) #ubuntu (1) #heroku (1) #git (1) #css (3) #cors (1) #same-origin-policy (1) #rake (1) #web-scraping (1) #ruby-on-rails (1) #brug (1) #elixir (1) #benchmark (1)