CORS practical overview: deploy it

Nahuel Molina | Silvio
7 min readJun 12, 2021

CORS is a reponse to the differents vulnerabilities a JSONP endpoint has. Avoiding the bypassing of same-origin policy security to work with it.

Axios was always aside of my study goals. Lastly, i find this tool an alternative very useful for web deployment. More exactly, i consider CORS an essential and modern practice. This article just has a docummenting purpose, gathering a vary amount of information, registering all that concepts a get in order i explore the web development area.

JSONP

JSON-P comes from JSON with Padding. This technique was used to read ordinary javascript, bypassing the same-origin policy, avoiding to manipulate DOM or XMLHttpRequest objects. See Practical JsonP injection.

Abusing JSONP with Rosetta Fash is a great case to read about, this show us how attackers are always working to exploit new vulnerabilities. It can be more interesting to explain in other blog, it get relevant from its technicity, which would put us away if we face it here.

Due to JSON-P endpoints becomes evidently very vulnerable, then it was replaced with CORS since 2009. It mainly, promise us to maintain a secure way to use our endpoints, reducing our vulnerabilities too. Today, we have vary tech tools that make use of this upcoming mechanism.

CORS: theory

All the motivation to write, is mainly to stand up all the power and protagonism of the theory. Something i find an urgence incovenient to resolve, is the habit to prove new things before already know what that things is based on. I am refering, to understand why it was created and why it is being replaced.

Basics

Firstly, what is CORS? “It’s an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources” says Mozilla Developer website. Due to browsers restricts cross-origin HTTP requests initiated from scripts, for security reasons, we should build the correct method and headers that will be analized for the server enable the actual request.

How i said before both XMLHttpRequest and the Fetch API follow the same-origin policy security naturaly, whose goal is to control interactions between two different origins.

Server’s mechanism to verify: preflighted requests

To make an Ajax request is posible through the preflighted requests, which are basically headers modified using the OPTIONS method as follows:

  • Origin – same as in simple requests.
  • Access-Control-Request-Method – the method.
  • Access-Control-Request-Headers – (Optional) a comma separated list of the custom headers being used.

As an example is:

Origin: https://humanwhocodes.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: NCZ

The mayority of browers support usage manage XMLHttpReques objects in requests to exchange data between the web site and a server to issue HTTP. Yes, i said mayority, Internet Explorer was an exception, until its disappearance this year. It employed XDomainRequest object which has a similar interface with XMLHttpRequest .

Preflight request are the core of CORS mechanism, you can aplied this with different request libraries. Edux-saga, GraphQL, jQuery and Modernizr are the most famous, but i am going to make use of Axios. The reason is that i take this as a more direct methodology, centered in requesting data.

Axios

This library, our resource, is promise-based, and this lets us write async/await code to perform XHR (the XMLHttpRequest’s short name) requests very easily. What with fetch()? Axios has quite a few advantages over the native Fetch API, explained as follows.

How you saw in this Post, the writing of headers is crucial. At its customization we have to figure out what response we want to get. Fetch() native function is limited, and the main diferences with a complete library, aim to its naming convention.

Making comparaisons and getting help of an user in Stackoverflow, we notice…

  • Fetch’s body = Axios' data
    Fetch’s body has to be stringified
  • Axios' data contains the object
    Fetch has no url in request object
  • Axios has url in request object
    Fetch request function includes the url as parameter
  • Axios request function does not include the url as parameter.
    Fetch request is ok when response object contains the ok property
  • Axios request is ok when status is 200 and statusText is 'OK'
    To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object

Why Axios? Ajax technology

“Ajax is a set of web development techniques using many web technologies on the client-side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behaviour of the existing page” says Wikipedia.

Ajax, Asynchronous JavaScript And XML, is a technology for creating fast and dynamic web pages. Utilizing it, axios is a wrapper around ajax technology through promises, implementing its encapsulation.

JQuery enters here, offering an option written in Javascript becoming at the end of the day in another library. Exploring Quora, i found that a great part of developers that respond comes to the same conclusion. In the core, each one have a common base, maybe ones have more vainila code than others. Axios prefer to not send cookies, requering a different set in headers, an extra step when JQuery already consider that. No one is actually better, but the last mentioned includes Ajax and also selectors, among others tool when axios is just created for requesting.

GraphQL are other aternatives to exploit Ajax’s posibilities, both are written in javascript bowing to facilitiate data’s exchange. GraphQLgives clients the power to ask for exactly what they need and nothing more”. This language provides to developers the responsabilities to “query and manipulate data”. It even can be intergated with JQuery, exploiting Ajax from there. We are touching a more complex atmosphere, an arquitecture that in a posible future replace API REST or maybe combines with it.

In this case we’re going to be using the classic API REST due to the low dificulty of this example and my very litle at GraphQL.

Deployment with Axios

I choosed Axios. You can use this tool, natively with Nodejsor in the browser in HTMLdocuments. If you prefer to deploy a React, Vue or Angular apps, it’s mandatory to install axios inside of this project.

npm install axios

Although, in a traditional HTML document, we can deploy a frontend more directly, avoiding an specific and extra knowledge. In case you are a backend developer who is exploring how the transfer data since browser for a better perspective, an HTML inyected with JS is sufficient. Alongside, we are going to be using http-server to run the frontend from localhost or my corresponding IP in the lan network. Let’s write…

pip install http-server -g

Then, whatever you want, create a folder and .js, .html and .css files inside this. Later, code the next in your prompt or CMD console.

http-server --proxy http:\localhost:8080

And to see the HTML in the your browser then… (if you have CMD)

start feed.html

In the example above i’m making a get request, to localhost server, requiring publications (posts). My purpose is basically to create a social media which publications and its likes or dislikes, comments and times shared, can be visualized utilizing this information from the database.

It gives me : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.An error which one i’m trying to resolve, basically it’s a problem with response headers i recieve from the server. Django application isn’t allowing a resources exchange, even when i implement the corsheaders library. Then, i verify the response i could get request the same origin through curl tool, as follows:

curl -I http://localhost:8000/api/posts

Resulting…

HTTP/1.1 301 Moved Permanently
Date: Thu, 10 Jun 2021 01:47:09 GMT
Server: WSGIServer/0.2 CPython/3.8.5
Content-Type: text/html; charset=utf-8
Location: api/posts/
Content-Length: 0
Vary: Origin
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin

Automatically, the curl request surely follows a same-origin policiy security, without CORS that use an asyncronous conversation. On a new attempt, i fixed the previous axios code getting a correct response at the frontend, just with the HTML document, avoiding to serve it.

As a conslusion, i should to distinguish that from a simple HTML, it’s not needed to implement preflighted request, indeed it is not served. Although, at the moment to serve pages, it’s mandatory to make use of corresponding headers, in front of the a real origin’s relation.

This way, the frontend is ready to retrieve simple data. Thanks to not bypassing policies, we can avoid vulnerables endpoints and don’t be aimed by cyber attackers. For more complex applications, a preflight request like the post one, going to be specified accurate to the natural necesities of this method.

GraphQl: definitive RestApi’s sucesor

GraphQl, depending on the environ you are comfortable with, it’s basically a library that allow a more molecular backend. Connecting separete servers, database, cache or the web app one, this library can be injected.

Used together at express.js, it promise us an army of resources from NPM for example apollo-server-express and graphql-tools , an example of deployment is here. Firstly, the application present an error or problem. That due to “neither express nor express-graphql permit the cors for default”, they not react in front of OPTIONS headers. It can be fixed, simply using its standard cors middleware, that ensures to the express server sets the proper HTTP header, enabling a secure resources’s consumption.

Final thoughts

Improve the performance of a web application is naturaly our first priority as creators in general. It’s mandatory to be aware of all the security requirements that a simple connection needs. Among the differents options at deployment, establish a double origins comes mainly with correcting the state of the endpoints, when we develop a API REST backend.

JSON format became a techonology concerns a growing are in order i study it. In my personal formation, it turn itself into an stressfull cycle without end. Although, i find on it a consolator sense, a personal perspective. Always searching my own sources, it’s such personal that bring me to respect more my self-development.

--

--

Nahuel Molina | Silvio

This place is what I need for writing about programming, learning in general, and for reading people's thoughts