Blog | G5 Cyber Security

CORS: Block Requests Serverside

TL;DR

This guide shows you how to block unwanted requests on your server using CORS (Cross-Origin Resource Sharing) headers. This is important for security, preventing malicious websites from accessing your data.

Understanding CORS

CORS is a browser security feature that restricts web pages from making requests to a different domain than the one which served the original HTML. Your server needs to explicitly allow cross-origin requests if you want them to succeed. Blocking requests serverside means telling the browser your server doesn’t accept requests from certain origins.

Steps to Block Requests Serverside

  1. Identify Allowed Origins: First, determine which domains should be allowed access to your API or resources. This is usually your own frontend domain(s).
  2. Configure Your Server: The method for setting CORS headers depends on your server technology (e.g., Apache, Nginx, Node.js with Express, Python with Flask). Here are examples:
    • Apache (.htaccess): Add the following to your .htaccess file.
      Header set Access-Control-Allow-Origin "https://your-allowed-domain.com"
    • Nginx (nginx.conf): Add the following to your server block configuration.
      add_header Access-Control-Allow-Origin "https://your-allowed-domain.com";
    • Node.js (Express): Use the cors middleware.
      const express = require('express');
      const cors = require('cors');
      const app = express();
      
      app.use(cors({
        origin: 'https://your-allowed-domain.com'
      }));
      
    • Python (Flask): Use the flask_cors extension.
      from flask import Flask
      from flask_cors import CORS
      
      app = Flask(__name__)
      CORS(app, resources={r"/api/*": {"origins": "https://your-allowed-domain.com"}})
      
  3. Block All Origins (Most Secure): To block all cross-origin requests, set the Access-Control-Allow-Origin header to a wildcard.
    Header set Access-Control-Allow-Origin "*"

    This is generally *not recommended* for production environments as it opens your API to potential security risks. It’s useful during development but should be replaced with specific allowed origins before deployment.

  4. Explicitly Deny Origins (Less Common): While you can’t directly “deny” origins with CORS headers, you achieve the same effect by *not* including them in your Access-Control-Allow-Origin configuration. If an origin isn’t listed, the browser will block the request.
  5. Check Your Configuration: After making changes, test thoroughly from different browsers and origins to ensure requests are blocked as expected.
    • Use your browser’s developer tools (Network tab) to inspect the response headers. Look for the Access-Control-Allow-Origin header.
    • Try making a request from an origin that should be blocked and verify you receive a CORS error in the console.

Important Considerations

Exit mobile version