Web API  

API Security Cheatsheet – A Detailed Guide

Introduction

APIs (Application Programming Interfaces) allow software systems to communicate with each other. They are used in mobile apps, web services, IoT devices, and more. But APIs are also a common target for hackers. If an API is not secure, it can expose sensitive data and allow unauthorized access.

This guide provides a complete cheatsheet on API security. Each topic is explained in simple language with short examples. The aim is to help you understand the core security practices to follow while designing or using APIs.

1. Authentication

Definition: Authentication verifies the identity of a user or system.

Example

GET /api/profile
Authorization: Bearer <access_token>

Important Point: Always use strong authentication methods like OAuth2 or JWT. Avoid passing credentials in the URL.

2. Authorization

Definition: Authorization controls what actions a user or system is allowed to perform after authentication.

Example

[Authorize(Roles = "Admin")]
public IActionResult DeleteUser(int id) { ... }

Important Point: Authentication tells who you are. Authorization tells what you can do.

3. HTTPS Only

  • Definition: Use HTTPS instead of HTTP to encrypt communication between client and server.
  • Example: Instead of http://api.example.com, use https://api.example.com
  • Important Point: Without HTTPS, data can be seen or changed during transfer. Use TLS 1.2 or higher.

4. Input Validation

Definition: Check all input from users to prevent attacks like SQL injection and script injection.

Example

if (!int.TryParse(id, out _))
{
    return BadRequest("Invalid ID");
}

Important Point: Never trust user input. Always validate and sanitize it.

5. Rate Limiting

Definition: Limit how many API requests a user can make in a given time.

Example

HTTP/1.1 429 Too Many Requests
Retry-After: 60

Important Point: This prevents abuse, such as brute-force login attempts or DoS attacks.

6. Use API Keys or Tokens

Definition: API keys or tokens are unique identifiers used to track and control API usage.

Example

GET /api/data
x-api-key: abc123xyz456

Important Point: Do not hardcode keys in your frontend code. Keep them secret.

7. Secure Endpoints

Definition: Restrict access to sensitive endpoints (like admin features or user data).

Example

[Authorize]
public IActionResult GetUserData() { ... }

Important Point: Do not expose internal or debug endpoints in production.

8. Use Proper HTTP Status Codes

Definition: Return the correct status code for different responses.

Example

  • 200 OK: Success
  • 401 Unauthorized: Missing or invalid token
  • 403 Forbidden: No access
  • 429 Too Many Requests: Rate limit hit

Important Point: Clear status codes help detect and handle errors properly.

9. JSON Web Tokens (JWT)

Definition: JWT is a compact, secure way to transmit user identity and claims.

Example (Decoded)

{
  "sub": "123456",
  "role": "Admin",
  "exp": 1627768290
}

Important Point: Use short expiration times. Validate the signature on the server.

10. Avoid Verbose Error Messages

Definition: Do not return detailed error messages that reveal stack traces or internal logic.

Example (Bad)

{
  "error": "System.NullReferenceException at Line 52 in AuthService.cs"
}

Example (Good)

{
  "error": "Something went wrong. Please try again."
}

Important Point: Keep error messages user-friendly and generic.

11. Use CORS Properly

Definition: Cross-Origin Resource Sharing (CORS) controls which websites can call your API.

Example

services.AddCors(options =>
{
    options.AddPolicy("AllowTrusted",
        builder => builder.WithOrigins("https://trusted.com").AllowAnyHeader().AllowAnyMethod());
});

Important Point: Do not allow all origins (*) in production.

12. Logging and Monitoring

Definition: Track API activity to detect abuse or attacks.

Example

_logger.LogWarning("Login failed for user: {username}", username);

Important Point: Log failed logins, 403 errors, 500 errors, and suspicious behavior.

13. Version Your API

Definition: Add version numbers to your API routes to prevent breaking changes.

Example

GET /api/v1/users

Important Point: Avoid making breaking changes to live API versions.

14. Protect Against Injection Attacks

Definition: Injection attacks like SQL injection happen when user input is sent directly to a query or command.

Example (Bad)

var sql = $"SELECT * FROM Users WHERE name = '{name}'";

Example (Good)

var sql = "SELECT * FROM Users WHERE name = @name";

Important Point: Use parameterized queries or ORM tools like Entity Framework.

15. Data Minimization

Definition: Only return the data that is necessary in the response.

Example: Instead of returning a full user object.

{
  "id": 1,
  "username": "john",
  "password": "1234", // BAD
  "email": "[email protected]"
}

Only return:

{
  "id": 1,
  "username": "john"
}

Important Point: Less data means less exposure.

16. Use Security Headers

Definition: Add HTTP headers to protect against browser-based attacks.

Example

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

Important Point: Set these headers in your server responses to prevent attacks like clickjacking.

17. Secure File Uploads

  • Definition: If your API accepts file uploads, validate the file type and size.
  • Example: Only allow .jpg or .png, limit to 2 MB.
  • Important Point: Store files outside of your main application folder. Scan for viruses if needed.

18. Disable Unused HTTP Methods

  • Definition: Only enable the HTTP methods that your API needs.
  • Example: If your API does not use PUT, disable it on the server.
  • Important Point: Fewer methods reduce the attack surface.

19. Security Misconfiguration

Definition: Leaving default settings or exposing unnecessary features can lead to vulnerabilities.

Example

  • Swagger docs open in production
  • Directory listing enabled
  • Admin console exposed

Important Point: Disable or hide debug tools and admin features in production. Always review security settings before deployment.

20. Broken Object Level Authorization (BOLA)

Definition: When users can access data that they shouldn’t by modifying object IDs in the request.

Example (Bad)

GET /api/users/12345  ← Exposes another user’s data

Important Point: Always check if the requesting user owns or has permission to access the resource.

21. Broken Function Level Authorization

  • Definition: When attackers call high-privilege functions (like deleting a user) without proper checks.
  • Example: A regular user calling an endpoint intended only for admins.
  • Important Point: Always verify both user identity and role before executing any critical action.

22. Excessive Data Exposure

  • Definition: Returning more data than necessary in API responses.
  • Example: Returning password hashes or internal flags in JSON response.
  • Important Point: Always control what fields are returned. Use DTOs or view models to limit data.

23. Mass Assignment

Definition: Allowing users to set fields they shouldn’t by submitting unexpected input.

Example (Bad)

{
  "username": "john",
  "isAdmin": true  // User should not control this
}

Important Point: Manually map input data. Never bind directly to internal models or entities.

24. Lack of Logging and Alerting

  • Definition: Failure to record key events or notify about suspicious activity.
  • Example: Login failures, access to sensitive data, or abuse of rate limits are not tracked.
  • Important Point: Log everything important. Set alerts for unusual behavior or repeated failures.

25. No API Gateway / WAF (Web Application Firewall)

  • Definition: Skipping a security layer that could filter and block attacks before they reach your app.
  • Example: Allowing direct access to backend services without inspection.
  • Important Point: Use an API gateway or WAF to apply rate limiting, IP filtering, authentication, and input validation centrally.

26. Insecure Deserialization

  • Definition: When attackers exploit serialized data formats (like JSON, XML) to run harmful code.
  • Example: Passing serialized objects that get deserialized without validation.
  • Important Point: Never trust serialized input from users. Always validate and restrict allowed object types.

27. Server-Side Request Forgery (SSRF)

Definition: When attackers make the server send requests to internal systems.

Example: Sending a request to.

{
  "url": "http://127.0.0.1:8080/internal-admin"
}

Important Point: Never allow users to supply full URLs. Validate the domain and restrict internal access.

28. API Deprecation and Sunset Policy

  • Definition: When old versions of APIs remain exposed and maintained without updates.
  • Example: /api/v1/login remains active even after /v3 is released.
  • Important Point: Set timelines for deprecation and communicate them. Remove old versions as soon as possible.

29. Secure Session Management

Definition: Managing user sessions securely using tokens or cookies.

Example

  • Use short-lived access tokens
  • Use refresh tokens for session renewal
  • Invalidate tokens after logout

Important Point: Never store tokens in localStorage in frontend apps. Use HttpOnly cookies where possible.

30. Mobile/API Client Hardening

Definition: Protect mobile apps or frontend clients from reverse engineering or token theft.

Example

  • Obfuscate client code
  • Use certificate pinning
  • Use dynamic secrets

Important Point: APIs alone are not secure if the client exposes secrets. Harden both ends.

31. Implement Content Security Policy (CSP)

Definition: CSP is a browser feature to prevent cross-site scripting (XSS) and data injection.

Example

Content-Security-Policy: default-src 'self'; script-src 'self'

Important Point: CSP is useful when your API is consumed by front-end apps running in browsers. Helps reduce frontend-driven attacks.

32. Avoid Client-Controlled Access Control

Definition: Never trust claims like isAdmin: true coming from the client.

Example (Bad)

{
  "username": "john",
  "isAdmin": true
}

Important Point: Roles and permissions must be verified on the server-side, not based on frontend flags.

33. Ensure Secure Cookie Flags

Definition: Use proper flags when setting cookies for session or authentication.

Example

Set-Cookie: auth=abc123; Secure; HttpOnly; SameSite=Strict

Important Point

  • Secure → Only send over HTTPS
  • HttpOnly → JS cannot access it
  • SameSite → Prevents CSRF attacks

34. Prevent Cross-Site Request Forgery (CSRF)

Definition: CSRF tricks a user into sending unwanted actions to your API.

Solution

  • Use SameSite cookies
  • Add CSRF tokens in forms
  • Block unintended referers

Important Point: Important for state-changing endpoints (like POST, PUT, DELETE) when using session cookies.

35. Apply Least Privilege for API Clients

Definition: Give API consumers (clients, apps, services) only the permissions they need.

Example

  • A mobile app can only read the profile
  • Admin dashboard can write/delete

Important Point: Define scopes in access tokens (e.g., read: user, write: admin) and enforce them strictly.

36. Use Secrets Management System

Definition: Never store credentials, API keys, or secrets in code or environment variables without secure handling.

Example Tools

  • Azure Key Vault
  • AWS Secrets Manager
  • HashiCorp Vault

Important Point: Rotate secrets regularly and audit access to secret stores.

37. Enable DDoS Protection

  • Definition: Protect your API infrastructure from Distributed Denial of Service (DDoS) attacks.
  • Example Tools: Cloudflare, AWS Shield, Azure DDoS Protection
  • Important Point: Use cloud-based protection to auto-scale and filter malicious requests.

38. Deploy API Security Scanners

Definition: Automated tools to find security issues in your API.

Example Tools

  • OWASP ZAP
  • Postman Security Scanner
  • Burp Suite
  • APIsec
  • StackHawk

Important Point: Run scans regularly in the CI/CD pipeline, especially before releasing public APIs.

39. Protect Against Replay Attacks

Definition: An attacker resends a valid request to perform the same action again.

Example Prevention

  • Add timestamps in requests
  • Use nonces (unique values)
  • Sign requests with HMAC

Important Point: Especially important for financial or transactional APIs.

40. Set Strict Payload Size Limits

Definition: Reject large or unexpected payloads to avoid DoS or buffer overflows.

Example

services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = 1048576; // 1MB
});

Important Point: Helps defend against resource exhaustion attacks.

41. Avoid Wildcard CORS and Headers

  • Definition: Allowing Access-Control-Allow-Origin: * or Access-Control-Allow-Headers: * opens security holes.
  • Important Point: Explicitly define trusted origins and headers. Use a wildcard only for public, non-sensitive APIs.

42. Protect Metadata Endpoints in Cloud Platforms

Definition: Some cloud providers expose instance metadata APIs (e.g., AWS /latest/meta-data) that can leak credentials.

Example Attack: SSRF targeting:

http://169.254.169.254/latest/meta-data/iam/security-credentials/

Important Point: Block server-side access to these endpoints if not needed.

43. Ensure Secure Deployment Practices

Definition: APIs should not be exposed through development or staging environments.

Checklist

  • Use CI/CD pipelines with code reviews
  • Deploy to hardened environments
  • Use container security scanning (e.g., Trivy, Snyk)

44. Align With Regulatory Compliance

Definition: Ensure API security meets laws like.

  • GDPR (for EU)
  • HIPAA (for health data)
  • PCI-DSS (for payments)

Important Point: Data encryption, audit logs, and access controls may be legally required.

45. Use HSTS (HTTP Strict Transport Security)

Definition: Instructs browsers to use HTTPS for all future requests.

Example Header

Strict-Transport-Security: max-age=31536000; includeSubDomains

Important Point: Reduces the chance of downgrade attacks or cookie theft via HTTP.

Conclusion

API security is not optional. A weak API can lead to data theft, fraud, or full system compromise. This cheatsheet covers the most important security practices with simple definitions and examples.

Always keep your APIs under regular review. Test them for vulnerabilities, and follow the latest security standards.