Cross-origin resource sharing

In the age of microservices, where web application components are decoupled and run as separate instances on totally different domains, the SOP presents some challenges.

Attempting to read some API data presented in JSON format would normally be denied by the SOP unless the origin triple matches. This is inconvenient, and applications become hard to develop and scale if we are constrained to the same domain, port, and scheme.

To loosen up the SOP, cross-origin resource sharing (CORS) was introduced, making developers happy again. CORS allows a particular site to specify which origins are allowed access to read content that is normally denied by the SOP.

The application server HTTP response can include an Access-Control-Allow-Origin header, which the client can use to determine whether it should complete the connection and retrieve the data.

Note

CORS is well-documented on the Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

We can see Spotify's public API CORS policy using curl:

root@spider-c2-1:~# curl -I https://api.spotify.com/v1/albums
HTTP/2 401 
www-authenticate: Bearer realm="spotify"
content-type: application/json
content-length: 74
access-control-allow-origin: *
access-control-allow-headers: Accept, Authorization, Origin, Content-Type, Retry-After
access-control-allow-methods: GET, POST, OPTIONS, PUT, DELETE, PATCH
access-control-allow-credentials: true
access-control-max-age: 604800
via: 1.1 google
alt-svc: clear

root@spider-c2-1:~#

This particular API is public and, therefore, will inform the client that all origins are allowed to read response contents. This is done with the value for Access-Control-Allow-Origin set to a wildcard: *. Private APIs will typically use a more specific value, such as an expected URL.

The Spotify server responds with other Access-Control headers, which specify which methods and headers are accepted, and whether credentials can be passed with each request. The CORS policy can get quite deep, but for the most part, we are concerned with what origin a particular target site allows.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset