CORS - Introduction For The New FE/BE Developer

I can assure you that one of the first issues you'll encounter when testing your newly developed product will be CORS. So what is CORS exactly?

Every web developer, either frontend or backend, may have come across this CORS policy violation (Cross-Origin Resource Sharing) error message at least once in their career.

The error itself is actually pretty informative. It basically tells you that the client-side is not one of the "whitelisted" origins to access the data being fetched. This is a security mechanism that browsers implement to prevent malicious users from accessing the data from a different origin.

Let's dive in a little bit.

First, what is CORS exactly? CORS stands for Cross-Origin Resource Sharing, which is a security mechanism that allows/prevents one origin to access a resource from a different origin. This is something that the server has control over to restrict who has access to the resource, how they can access the data, for example, which HTTP methods, HTTP headers, etc are allowed. At its core, you can treat it as a protocol allowing web applications to request resources from different domains securely. It's a dance of headers and requests, where the server dictates who can access its resources.

Same Origin Policy vs Cross Origin Resource Sharing

The Same-Origin Policy (SOP) is a critical security mechanism that restricts web pages from making requests to a different origin than the one that served the web page. CORS, on the other hand, is a tool to relax those restrictions under controlled conditions. It allows servers to specify who can access their assets and how.

CORS Mechanism

CORS works by adding new HTTP headers that allow servers to declare which origins are permitted to access the resources. For example, the Access-Control-Allow-Origin header can specify an allowed origin, or it can use * to allow requests from any origin. However, using * in most cases is discouraged for sensitive resources due to security concerns.

Let's take a look at an example using NodeJS & Express:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

// CORS with specific options
const corsOptions = {
  origin: 'https://example.com',
};

app.get('/data', cors(corsOptions), (req, res) => {
  res.json({ message: 'This route is CORS-enabled for an allowed origin.' });
});

app.listen(3000, () => console.log('Server running on port 3000'));

Here we're basically using the cors middleware that is applied globally to allow Cross-Origin Resource Sharing (CORS) from any origin, enabling client applications from different domains to access the server. Additionally, it showcases a more complex setup where CORS settings are customized for a specific route, allowing requests only from a specified origin and setting specific methods and headers.

Now, let's take a look at another example, but this time using Python & FastAPI:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Simple CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# CORS for specific origins
origins = [
    "http://example.com",
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET"],
    allow_headers=["X-Custom-Header"],
)

@app.get("/data")
async def get_data():
    return {"message": "This route is CORS-enabled for specific origins."}

This simple snippet demonstrates two approaches: a global application of CORS allowing all origins, methods, and headers, and a more restrictive approach where CORS is configured for specific origins, methods, and headers on all routes, illustrating how to control access to your API more granularly.

Implementing CORS correctly is a balancing act. Developers must ensure their web applications are accessible to legitimate users and services while protecting against unauthorized access. Understanding CORS is crucial for any developer working on the web, as it directly impacts the security and functionality of web applications.



Tags:

Related Articles

Lab as a Service in DAZN

Read More

Why Makefile is One of My Essentials Tools in Every Software Project

Read More

Markdown Linters for Your Docs Repo

Read More

Monitor Your Hosted Local Machines with OpenTelemetry Collector Contrib

Read More