Security  

๐Ÿ” API Security Explained: Rate Limiting, CORS, SQL Injection, CSRF, XSS & More

APIs are the backbone of modern applicationsโ€”mobile apps, web apps, microservices, cloud platformsโ€”you name it. But with great connectivity comes great security challenges. Attackers constantly exploit weak APIs to steal data, overload systems, inject malicious code, or impersonate users.

In this article, we break down the essential API security mechanisms that every developer, architect, or DevSecOps engineer must understand.

Letโ€™s explore them one by one. ๐Ÿ‘‡

Introduction

Every API exposed to the internet is a potential attack surface. Common threats include:

  • API overload (DDoS)

  • Unauthorized access

  • Code injections

  • Cross-site attacks

  • Data theft

  • Session hijacking

To protect APIs, we use a combination of defensive techniques, including throttling, authentication, validation, encryption, and secure coding practices.

This article covers some of the most important techniques with practical insights.

Rate Limiting

Rate Limiting prevents clients from making excessive requests to your API within a given time frame.

Why it matters

Hackers may:

  • Send thousands of requests/second to bring your API down

  • Attempt brute-force login attacks

  • Abuse free APIs

Rate limiting protects your infrastructure, improves stability, and ensures fair usage.

Types of Rate Limiting

  1. Fixed Window
    Allows X requests per time window (e.g., 100 requests per minute).

  2. Sliding Window
    More accurate, counts requests from the last N minutes.

  3. Token Bucket / Leaky Bucket
    Popular in cloud & microservices (AWS API Gateway, Azure APIM).

Implementation examples

  • ASP.NET Core: RateLimiter middleware

  • NGINX: limit_req_zone

  • API Gateway: Built-in throttling policies

  • Redis-backed throttling for distributed systems

What it protects against

  • DDoS bursts

  • Abuse of login or OTP APIs

  • Overuse of free-tier APIs

CORS (Cross-Origin Resource Sharing)

CORS controls which domains are allowed to access your API from a browser.

Example

Your API is hosted at:

api.example.com

Your frontend is at:

app.example.com

Without CORS, browsers block cross-domain AJAX calls.

Why CORS matters

  • Prevents malicious websites from calling your API without permission.

  • Protects cookies and JWT tokens from being leaked cross-origin.

Config Examples

ASP.NET Core

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowApp",
        b => b.WithOrigins("https://app.example.com")
              .AllowAnyHeader()
              .AllowAnyMethod());
});

Common Mistake

Donโ€™t do this in production:

AllowAnyOrigin()

It opens your API to the public, risking data leakage.

SQL & NoSQL Injections

Injection attacks happen when user input is executed as code inside the database.

SQL Injection Example

Bad code:

SELECT * FROM Users WHERE Name = '" + username + "'";

Attacker enters:

' OR 1=1 --

Result:

  • Entire user table is exposed

  • Authentication bypassed

Fix

  • Use parameterized queries

  • Use ORM frameworks (EF Core, Hibernate)

  • Validate input length & patterns

NoSQL Injection Example (MongoDB)

Bad:

db.collection('users').find({ name: req.query.name })

Attack:

{"$ne": ""}

Fix:

  • Whitelist allowed parameters

  • Use schema validation ([MongoDB Validator])

  • Sanitize JSON input

Firewalls

Firewalls act as the first line of defense by filtering traffic.

Types of Firewalls for APIs

  1. Network Firewall
    Blocks unauthorized IPs/ports.

  2. WAF (Web Application Firewall)
    Protects against:

    • XSS

    • SQL Injection

    • Bot attacks

    • Broken authentication

  3. API Gateway Security
    Adds rate limiting, JWT validation, throttling.

Popular Tools

  • Azure WAF

  • AWS WAF

  • Cloudflare

  • NGINX App Protect WAF

Firewalls significantly reduce attacks before they hit your application.

VPNs (Virtual Private Networks)

VPNs restrict API access only to users connected through a secure network tunnel.

Why enterprises use VPNs

  • Protect internal APIs (HR, Finance, Admin Panel)

  • Restrict access to private microservices

  • Enforce Zero-Trust policies

  • Prevent IP spoofing or external attacks

Example

Admin APIs are allowed only from the company VPN or office IPs.

CSRF (Cross-Site Request Forgery)

CSRF tricks a logged-in user into performing an unwanted action on your API.

Example

User is logged in at:

bank.com

Malicious site secretly sends:

POST https://bank.com/transfer

If the bank API doesn't validate CSRF tokens, money could be transferred without user permission.

How to protect against CSRF

  • Use anti-forgery tokens

  • Use SameSite cookies

  • Require JWT in Authorization header (not cookie)

  • Block cross-site cookies with:

    Set-Cookie: SameSite=Strict
    

XSS (Cross-Site Scripting)

XSS allows attackers to inject malicious JavaScript into web pages or API responses.

Example attack

User posts:

<script>alert('Hacked!')</script>

If stored and returned via API response โ†’ browsers execute it.

Types of XSS

  1. Stored XSS โ€“ attackerโ€™s script stored in DB

  2. Reflected XSS โ€“ script returned via API response

  3. DOM-XSS โ€“ executed by client-side JS

How to prevent XSS

  • HTML encode outputs

  • Sanitize inputs on API and frontend

  • Use Content Security Policy (CSP)

  • Disable inline JavaScript

  • Validate file uploads and metadata

๐Ÿ”š Conclusion

API security is not a single feature โ€” itโ€™s a layered defense strategy.
To secure your APIs, always combine:

  • Rate Limiting (protect traffic & abuse)

  • CORS (control who can call your API)

  • SQL/NoSQL Injection Prevention

  • Firewalls & WAF

  • VPN for private APIs

  • CSRF protection

  • XSS prevention & output encoding