Understanding Access-Control-Allow-Origin (CORS) and How to Bypass it

Mohammed Hussain Alrabrabah
3 min readNov 9, 2023

--

Introduction

Cross-Origin Resource Sharing (CORS) is a vital security feature implemented by web browsers. It ensures that a web page can only make requests to the same domain from which it was served. This article will delve into what CORS is, where it happens, demonstrate an example of bypassing it using a Chrome extension, and guide you through configuring JavaScript code to bypass CORS. Additionally, we’ll explore why CORS restrictions are enforced in API calls.

What is CORS?

CORS is a security mechanism that safeguards web applications from malicious scripts that could potentially steal sensitive data or perform harmful actions on behalf of the user. It restricts web pages from making requests to a different domain than the one from which they originated.

Where Does CORS Happen?

CORS comes into play when a web page, loaded in a browser, attempts to request resources (like data or services) from a different domain using JavaScript. This security feature is enforced by the browser to prevent unauthorized access to sensitive information.

Bypassing CORS with Chrome Extensions

Chrome extensions like “Allow CORS: Access-Control-Allow-Origin” provide a workaround to temporarily disable CORS restrictions for development or testing purposes. This extension injects the necessary headers into the response, effectively allowing cross-origin requests. However, it’s crucial to exercise caution and only use such extensions in controlled environments.

Configuring JavaScript Code to Bypass CORS

While bypassing CORS using extensions is convenient for testing, it’s not a feasible solution for production applications. To handle CORS programmatically, you can use techniques like JSONP or make requests through a proxy server on your domain. JSONP works by embedding a script tag in the HTML that fetches data from a different domain. This technique circumvents the same-origin policy.

Why Does CORS Happen in API Calls?

CORS restrictions are primarily enforced in API calls to prevent unauthorized access to sensitive data or services. For instance, if a web application hosted on example.com attempts to make an API request to api.example.net, the browser will block the request due to CORS restrictions. This ensures that only trusted domains can access the API.

Code Example Using CORS

To demonstrate bypassing CORS using a proxy server, I’ll provide an example using Node.js and the cors-anywhere package. This package acts as a reverse proxy, adding the necessary CORS headers to allow cross-origin requests.

First, you’ll need to have Node.js installed on your system. Then, follow these steps:

  • Create a new directory for your project and navigate into it.
  • Initialize a new Node.js project by running npm init -y in your terminal.
  • Install the cors-anywhere package by running npm install cors-anywhere.

Now, you can create a simple server using the cors-anywhere package:

const cors_proxy = require('cors-anywhere');

// Define the port for the proxy server
const PORT = 3000;

// Start the proxy server
cors_proxy.createServer({
originWhitelist: [], // Allow all origins
}).listen(PORT, () => {
console.log(`CORS Anywhere is running on http://localhost:${PORT}`);
});

Now, you can make requests to your proxy server, which will add the necessary CORS headers to allow cross-origin requests. For example, if you want to access https://api.example.com/data, you would make the request to http://localhost:3000/https://api.example.com/data

Another example using axios:

  • Setting up the server (Node.js):
const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 3000;

// Enable CORS for all routes
app.use(cors());

// Define a simple endpoint
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from the server!' });
});

app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
  • Using Axios to make a request:
const axios = require('axios');

// Make a GET request to the server we just set up
axios.get('http://localhost:3000/api/data')
.then(response => {
console.log('Response from server:', response.data);
})
.catch(error => {
console.error('Error:', error);
});

In this example, we’re using the Express framework for Node.js to set up a simple server on localhost at port 3000. We’ve enabled CORS for all routes using the cors middleware.

The server has one endpoint (/api/data) which responds with a JSON message.

Next, we use Axios to make a GET request to this server. Since we’ve set up CORS correctly on the server, the request should go through without any issues.

Conclusion

Understanding CORS is crucial for web developers working on applications that interact with external resources. While it’s important for security, it can sometimes pose challenges during development. By utilizing techniques like proxy servers, JSONP, or Chrome extensions for testing, developers can navigate around CORS restrictions. However, it’s essential to implement secure and robust solutions that comply with CORS policies to ensure the safety of web applications in production environments.

--

--

Mohammed Hussain Alrabrabah

AI Lead with a passion for high-performance & cloud computing. Pursuing a Master's in the same. Expertise in cutting-edge AI solutions.