Understanding CORS- Why It’s Important and How to Secure Your API

Dilanka Muthukumarana
4 min readNov 25, 2024

--

In the world of web development, ensuring secure communication between your application and its backend services is important. One of the most common issues that arise when working with APIs is related to Cross-Origin Resource Sharing (CORS).

This article will explain CORS in simple terms, why it is important, and how you can secure your API against potential misuse.

What is CORS?

The Problem- Same-Origin Policy

Browsers are designed with a security feature called the Same-Origin Policy. This policy restricts web pages from making requests to a different domain (origin) than the one that served the web page.

For example:

  • If your website is hosted at https://example.com, it cannot make API requests to https://api.example.com without proper configuration.
  • This restriction prevents malicious websites from accessing sensitive data on other domains.

However, there are many legitimate cases where cross-origin requests are needed. For instance, your web app might need to fetch data from an API hosted on a different subdomain.

Enter CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that allows your server to specify which origins are permitted to access its resources.

It acts like a “security guard,” controlling who gets to talk to your backend.

A Simple Analogy- The Restaurant and the Kitchen

Imagine your API is a kitchen in a restaurant, and your web app is the waiter.

  • Normally, only the restaurant’s waiters (your app) should be allowed to access the kitchen.
  • Without a guard (CORS), anyone from the street could enter the kitchen and place orders, potentially causing problems.
  • With CORS, you can set up a “security guard” who ensures only trusted waiters (specific websites) can enter.

What Happens Without Proper CORS Configuration?

  1. Unauthorized Access:
    An attacker could create a fake website (https://fake-app.com) that makes requests to your API.
  2. The attacker could use your API to;
  • Steal data by impersonating legitimate users.
  • Abuse your resources by spamming your endpoints.
  • Data Theft via Malicious Websites:
    If a user is logged into your app and visits a malicious website, that site could secretly make API calls on behalf of the user, leading to stolen data.

How to Fix CORS Issues?

Step 1- Add CORS Headers

You can configure your API to allow only trusted origins.

For example

Access-Control-Allow-Origin: https://trusted-website.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Authorization, Content-Type
  • Access-Control-Allow-Origin- Specifies which origins can access your API.
  • Access-Control-Allow-Methods- Specifies allowed HTTP methods like GET and POST.
  • Access-Control-Allow-Headers- Specifies allowed custom headers, such as Authorization.

CORS Configuration Example

Here is how you can configure CORS in common platforms

1. Spring Boot (Java Backend)

In a Spring Boot application, you can configure CORS globally or for specific endpoints:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://trusted-website.com")
.allowedMethods("GET", "POST")
.allowedHeaders("Authorization", "Content-Type");
}
}

2. AWS API Gateway

For APIs hosted on AWS API Gateway:

  • Navigate to the method settings for your API.
  • Enable CORS and specify allowed origins, methods, and headers.

Step 2- Test Your Configuration

After setting up CORS, you should test it to ensure it works as expected. Use browser developer tools to check the network requests:

  1. Make an API call from your application.
  2. Inspect the response headers to confirm the presence of CORS headers (e.g., Access-Control-Allow-Origin).

A Real-World Example

Scenario- A Restaurant Reservation System

You run a restaurant reservation system with

Your app fetches reservation data from the API, but you do not want other websites to abuse your API. Without CORS, a malicious site (https://fake-reservations.com) could

  1. Fetch reservation data from your API.
  2. Use it to impersonate users or spam your endpoints.

The Fix

Add CORS to your API to allow requests only from https://myrestaurant.com:

Access-Control-Allow-Origin: https://myrestaurant.com

Step 3: What About Public APIs?

If your API needs to be accessed by multiple third-party clients, you can

  1. Allow Specific Origins- Maintain a list of trusted origins.
  2. Use API Keys or Tokens- Require authentication for API access.
  3. Set Limits- Add rate-limiting to prevent abuse.

FAQs About CORS

Q: Can I allow all origins using *?

Yes, but it’s risky. Allowing * means any website can access your API, which defeats the purpose of CORS.

Q: What is a preflight request?

For non-simple requests (like POST with custom headers), the browser sends a preflight request (an OPTIONS request) to check if the API allows the intended operation.

Q: What if I need dynamic origins?

For APIs with dynamic origins (e.g., partner integrations), you can use server-side logic to verify the origin and set the Access-Control-Allow-Origin header dynamically.

Key Takeaways

CORS is a critical security feature that protects your API from unauthorized access. By setting up CORS correctly, you ensure that only trusted applications can interact with your backend.

  1. Always specify trusted origins using the Access-Control-Allow-Origin header.
  2. Use tools like browser developer tools to debug CORS issues.
  3. For public APIs, implement additional security measures like API keys and rate limits.

By understanding and configuring CORS properly, you can keep your APIs secure while enabling legitimate cross-origin requests.

If you enjoyed this article and found it insightful, please consider supporting it with some 👏 claps, sharing it 🔄, and following me on LinkedIn 🔗. I value your feedback and would love to hear your opinions and ideas 💡. Don’t hesitate to comment below with topics you’re interested in or thoughts you’d like to share 💬. Let’s keep the conversation going and explore together!

Are you looking for expert freelance services or professional consultation? Visit https://devinsights.tech/ for top-notch solutions tailored to your needs. Let’s turn your vision into reality!

--

--

Dilanka Muthukumarana
Dilanka Muthukumarana

Written by Dilanka Muthukumarana

TOGAF® Enterprise Architecture Practitioner | Consultant For Services: https://devinsights.tech/ Buy me a coffee: https://buy.stripe.com/8wMbMpdvO31ycsUbII

No responses yet