---
title: "How to Harden Your API for Better Security"
description: "Protect your APIs from increasing attacks by implementing strong authentication, input validation, and monitoring practices for enhanced security.."
canonicalUrl: "https://zuplo.com/learning-center/how-to-harden-your-api-for-better-security"
pageType: "learning-center"
authors: "nate"
tags: "API Security, API Best Practices, JSON Schema"
image: "https://zuplo.com/og?text=How%20to%20Harden%20Your%20API"
---
**APIs are under constant attack.** With over 83% of web traffic now API-driven,
they’ve become a prime target for hackers. Recent breaches, like the 2022
[T-Mobile](https://www.t-mobile.com/) incident exposing 37 million accounts,
highlight the risks. The average cost of an API breach? $4.88 million. Yet, 40%
of businesses still lack proper protections.

**Here’s how to secure your APIs:**

- **Strengthen Authentication:** Use [OAuth 2.0](https://oauth.net/2/),
  [OpenID Connect](https://de.wikipedia.org/wiki/OpenID_Connect), short-lived
  tokens, and role-based access controls (RBAC).
- **Validate Inputs:** Sanitize data to block injection attacks.
- **Limit Requests:** Set
  [rate limits](https://zuplo.com/docs/policies/rate-limit-inbound) to prevent
  abuse and DDoS attacks.
- **Encrypt Data:** Use HTTPS, TLS, and secure data storage.
- **Monitor and Test:** Run regular scans, penetration tests, and monitor
  traffic for anomalies.
- **Reduce Attack Surface:** Remove unused endpoints and isolate internal APIs.

**Quick Tip:** [API gateways](./2025-05-30-choosing-an-api-gateway.md), like
Zuplo, centralize security, manage access, and monitor traffic effectively.

APIs drive modern systems, but without proper defenses, they’re a liability.
Start implementing these measures today to protect your data and systems. :

## Set Up Strong User Authentication

With API attacks skyrocketing by over 400% in the past year, ensuring strong
authentication is no longer optional - it's a must. Protecting endpoints
requires a robust approach to user authentication.

### Configure [OAuth 2.0](https://oauth.net/2/) and [OpenID Connect](https://de.wikipedia.org/wiki/OpenID_Connect)

OAuth 2.0 and OpenID Connect (OIDC) are essential frameworks for securing API
authentication. While OAuth 2.0 focuses on managing authorization, OIDC layers
in authentication to enhance security.

Here’s how to implement OAuth 2.0 securely:

- **Enable PKCE** to prevent authorization code interception.
- **Validate the** `state` **parameter** to guard against CSRF attacks.
- **Enforce strict matching** for redirect URIs.
- **Require HTTPS** for all redirect URIs to ensure secure communication.

For token management, follow these best practices:

- Use **short lifespans** for access tokens (15–30 minutes).
- Rely on **refresh tokens** to issue new access tokens without requiring users
  to re-authenticate.
- **Monitor token usage** to detect any unusual activity.
- Enable **token revocation** to promptly invalidate compromised tokens.

These steps ensure secure handling of
[API keys](./2022-12-01-api-key-authentication.md) and JWTs while minimizing
vulnerabilities.

### Set Up API Keys and JWTs

Properly securing API keys and
[JSON Web Tokens](./2025-04-18-jwt-api-authentication.md) (JWTs) is critical for
protecting your API. If you're not sure about the difference between them, check
out our
[API key vs JWT comparison](./2022-04-25-jwt-vs-api-key-authentication.md).
Here’s how to safeguard API keys:

- Store keys in **environment variables**.
- Use **dedicated secrets managers** like
  [HashiCorp Vault](https://www.vaultproject.io/) or
  [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/).
- Employ **backend proxy servers** to keep keys out of client-side code.

<YouTubeVideo videoId="ooyOmiczY1g" />

For JWTs, consider these security measures:

- Always transmit tokens over **HTTPS**.
- Store tokens in **HttpOnly cookies** with the Secure flag enabled.
- Validate key claims like `iss` (issuer) and `aud` (audience).
- Implement **token rotation** and maintain a **revocation list** to handle
  compromised tokens effectively.

### Add Role-Based Access Controls

[Role-Based Access Control](./2025-01-28-how-rbac-improves-api-permission-management.md)
(RBAC) restricts access to resources based on user roles, significantly reducing
the risk of unauthorized access. Data breaches caused by malicious insiders cost
companies an average of $4.99 million, making RBAC a critical safeguard.

| Role Type | Access Level | Typical Permissions                |
| --------- | ------------ | ---------------------------------- |
| Admin     | Full         | Complete system access             |
| Developer | Elevated     | Project and environment management |
| Member    | Limited      | Basic operations only              |

To maintain effectiveness, regularly review RBAC configurations and adhere to
the principle of least privilege. This ensures users only have access to what
they need - nothing more.

Here's a tutorial on how to add RBAC to your API using Zuplo:

<YouTubeVideo videoId="Xo02a8rzQKc" />

## Validate and Clean Input Data

After implementing strong authentication measures, the next step is validating
input data. This process is essential to shield your API from malicious data and
potential vulnerabilities.

### Check Data Types and Formats

Validating data types and formats is a key defense against injection attacks and
ensures data remains consistent. Here's how you can structure your validation
approach:

| **Validation Type** | **Purpose**                | **Rule Example**          |
| ------------------- | -------------------------- | ------------------------- |
| Data Type           | Ensures correct format     | Integer: 0-9 only         |
| Length              | Prevents buffer overflow   | String: 2-50 characters   |
| Range               | Maintains logical bounds   | Age: 0-120 years          |
| Pattern             | Validates specific formats | Email: "name\@domain.com" |

To strengthen your input validation, apply both syntactic and semantic checks:

- **Syntactic Validation**: Focuses on structure. For example, verify Social
  Security Numbers (SSNs), dates in MM/DD/YYYY format, or proper currency
  formats (e.g., $XX.XX).
- **Semantic Validation**: Ensures data makes logical sense. For instance:
  - Confirm start dates occur before end dates.
  - Check that price ranges align with product categories.
  - Verify zip codes match their respective states.

For syntactic validation, try to schematize your inputs using a format like
[JSON Schema](./2025-04-15-how-api-schema-validation-boosts-effective-contract-testing.md)
so schemas can be reused across different endpoints. One other benefit of JSON
schema is that you can embed it directly into your OpenAPI
[API definition](./2024-09-25-mastering-api-definitions.md) and validate inputs
using your docs. Here's how you can do that using Zuplo:

<YouTubeVideo videoId="POkuwh0iAbc" />

Once you've enforced these rules, take it a step further by sanitizing inputs to
remove any harmful characters.

### Remove Harmful Input Characters

Sanitizing input is critical to block injection attacks. For example, in late
2023, a security breach exploited unsanitized inputs, leading to the theft of
over 2 million email addresses.

**Key Steps for Sanitization:**

1. **Implement Character Allowlisting**  
   Only permit the following:
   - Letters (a-z, A-Z)
   - Numbers (0-9)
   - Approved special characters (e.g., @, #, $)
2. **Normalize Data**
   - Convert text into a consistent, canonical form.
   - Strip out invalid or extraneous characters.
   - Standardize line endings.
   - Properly handle UTF-8 encoding to avoid misinterpretation.
3. **Use Prepared Statements**  
   Protect against SQL injection by securely binding parameters. This ensures
   that commands and data are handled separately, reducing risk.

**Pro Tip:** Always validate inputs on the server side. While client-side checks
are useful, they can be easily bypassed by attackers. Server-side validation
provides a much-needed safety net.

## Set Request Limits

[Request limits (aka API Rate Limits)](./2025-01-24-api-rate-limiting.md) are
essential for protecting your API from abuse while ensuring consistent
performance. By controlling how many requests clients can make within specific
timeframes, rate limiting prevents server overload and keeps your system running
smoothly.

### Define Request Quotas

To set effective
[request quotas](https://zuplo.com/docs/policies/quota-inbound), consider your
API's capacity and typical user behavior. Use thorough testing and real-world
usage data to find the right balance between accessibility and protection.

<YouTubeVideo videoId="gO5e9GdvuT0" />

| Time Window | Quota                  | Purpose                    |
| ----------- | ---------------------- | -------------------------- |
| Per Second  | 10-50 requests         | Prevent rapid-fire attacks |
| Per Minute  | 100-500 requests       | Control bursts of traffic  |
| Per Hour    | 1,000-5,000 requests   | Manage sustained usage     |
| Per Day     | 10,000-50,000 requests | Set overall boundaries     |

Include response headers to help users manage their request limits:

- `X-RateLimit-Limit`: The maximum number of requests allowed.
- `X-RateLimit-Remaining`: The number of requests left in the current window.
- `X-RateLimit-Reset`: The time until the limit resets.

These headers not only improve transparency but also guide users in managing
their API usage. Additionally, be prepared to adjust these limits dynamically
based on traffic patterns.

### Adjust Limits Based on Traffic

[Dynamic rate limiting](https://zuplo.com/blog/2022/04/28/dynamic-rate-limiting)
allows your API to adapt to fluctuating traffic and usage patterns. By
monitoring performance metrics, you can tweak limits in real time to maintain
service quality.

Here are some key strategies for dynamic rate limiting:

- **Monitor Server Load**  
  Keep an eye on CPU usage, memory, and response times. If these metrics exceed
  acceptable thresholds, automatically lower the request limits to ease the
  burden on your servers.
- **Implement Intelligent Retry Mechanisms**  
  Use a `Retry-After` header to tell clients when they can safely retry their
  requests, reducing unnecessary traffic during high-load periods.
- **Use Priority Queuing**  
  During peak traffic, prioritize critical requests over less important ones.
  This ensures essential operations are processed while throttling
  lower-priority traffic more aggressively.

A great example of dynamic rate limiting in action is
[GitHub](https://github.com/)'s API. Authenticated users can make up to 5,000
requests per hour, and the `/rate_limit` endpoint provides real-time updates on
their usage status.

For consistent enforcement, especially in distributed environments, implement
[distributed rate limiting](https://zuplo.com/docs/articles/per-user-rate-limits-using-db)
with a centralized data store. This ensures accurate tracking and enforcement of
limits across all your API servers.

## Protect Data Storage and Transfer

Once you've implemented strong authentication and rate limiting, the next step
is safeguarding your data - both while it's being transmitted and when it's
stored. Encryption protocols and standards are key to keeping your data safe
from unauthorized access and breaches.

### Use HTTPS and TLS

HTTPS combined with TLS encryption is the backbone of secure API communication.
[Stack Overflow](https://stackoverflow.com/) emphasizes its importance:

> "Every web API should use TLS (Transport Layer Security). TLS protects the
> information your API sends (and the information that users send to your API)
> by encrypting your messages while they're in transit".

To ensure robust HTTPS and TLS protection, follow these steps:

- Install SSL certificates from trusted certificate authorities.
- Configure TLS 1.3 (or at least TLS 1.2) on your API servers.
- Regularly rotate your certificates and handle them securely.
- Enable HTTP Strict Transport Security (HSTS) to enforce HTTPS connections.

For added security, consider implementing mutual TLS (mTLS), which provides an
extra layer of protection by authenticating both the client and the server.

### Secure Stored Data

While encrypting data in transit is crucial, protecting data at rest is just as
important. Use the following strategies to secure stored data effectively:

| **Protection Layer** | **Implementation**               | **Purpose**                      |
| -------------------- | -------------------------------- | -------------------------------- |
| Data Classification  | Categorize data by sensitivity   | Identify encryption requirements |
| Storage Encryption   | Leverage platform-native tools   | Safeguard data at rest           |
| Key Management       | Store keys separately            | Protect encryption keys          |
| Access Controls      | Apply identity-based permissions | Restrict data access             |
| Monitoring           | Log activity consistently        | Detect unusual behavior          |

For sensitive information, double encryption can add another layer of security.
Use a key encryption key (KEK) to secure your data encryption key (DEK),
providing an extra safeguard.

Additionally, configuring HTTP security headers can further minimize your
exposure to potential attacks.

### Add Security Headers

Security headers act as a shield against common vulnerabilities.
[OWASP](https://owasp.org/) highlights their importance:

> "HTTP Headers are a great booster for web security with easy implementation.
> Proper HTTP response headers can help prevent security vulnerabilities like
> Cross-Site Scripting, Clickjacking, Information disclosure and more.".

Here are some essential security headers to include:

- **Content-Security-Policy (CSP):** Helps block cross-site scripting (XSS) and
  injection attacks.
- **Strict-Transport-Security:** Ensures all connections use HTTPS.
- **X-Content-Type-Options:** Prevents MIME-type mismatches.
- **CORS Headers:** Regulates cross-origin resource sharing to control access.

## Use API Gateways for Security

API gateways act as a centralized hub for authentication, monitoring, and access
controls, offering a secure entry point for your APIs.

### Manage Access Controls Centrally

Centralizing access controls through an API gateway helps mitigate risks
associated with distributed authentication systems.

Here’s how you can implement centralized access controls effectively:

- **Configure Gateway Authentication**: Set up authentication at the gateway
  level using standard protocols. This ensures consistent security practices and
  simplifies the overall system.
- **Define Role-Specific Policies**: Create detailed access policies tailored to
  user roles. Deny access by default and allow only requests that meet specific
  security requirements.
- **Integrate Identity Management**: Incorporate external identity providers
  like OAuth and OpenID Connect to streamline and unify identity management.

If you think that setting up an API gateway is a months-long process, you'd
normally be right, but there are now developer-first API gateways on the market,
like Zuplo, that make getting set up a breeze. All you need is an OpenAPI
specification to add authentication, rate limiting, RBAC, and everything else we
talked about above to your API in 10 minutes:

<YouTubeVideo videoId="uZnKoGQNhrQ" />

Once access controls are in place, the next step is monitoring traffic to detect
threats early and manage loads dynamically.

### Monitor Traffic and Set Limits

API gateways also empower you to monitor traffic in real time and enforce rate
limits, which is critical for maintaining security during high-traffic events.
For example, an e-commerce platform successfully navigated the challenges of
seasonal sales by using gateway-based load balancing and rate limiting.

| **Monitoring Feature** | **Security Benefit**                        | **Implementation Priority** |
| ---------------------- | ------------------------------------------- | --------------------------- |
| Traffic Analysis       | Spot unusual patterns and potential attacks | High                        |
| Request Logging        | Track usage and investigate incidents       | High                        |
| Rate Limiting          | Protect against DDoS attacks and abuse      | Critical                    |
| Error Tracking         | Identify and address vulnerabilities        | Medium                      |

To enhance security further:

- Enable logging to monitor usage and flag anomalies.
- Leverage AI tools for real-time threat detection.
- Set up automated alerts to respond quickly to potential threats.
- Regularly review metrics to refine and improve security policies.

For large-scale deployments, consider using infrastructure-as-code (IaC) to
maintain consistent API gateway configurations across all environments. This
approach minimizes configuration errors and ensures uniform enforcement of
security protocols.

## Test Security Regularly

Testing is the final step in strengthening your API's defenses, helping to
uncover weaknesses before attackers can exploit them. A recent study revealed
that 94% of companies have faced
[API security](https://zuplo.com/blog/2022/12/01/api-key-authentication) issues
in production, with malicious API traffic surging by 117% between July 2021 and
July 2022.

### Run Security Scans

Regular security scans are essential for identifying and addressing
vulnerabilities. Pair automated scans with manual reviews to ensure
high-severity issues are thoroughly examined.

| Scan Type                     | Frequency     | Priority Level | Key Focus Areas                             |
| ----------------------------- | ------------- | -------------- | ------------------------------------------- |
| Automated Vulnerability Scans | Weekly        | High           | Configuration issues, known vulnerabilities |
| Authenticated Scans           | Quarterly     | Critical       | Access control, data exposure               |
| Full Penetration Tests        | Annually      | Essential      | Complex attack scenarios                    |
| Post-Change Scans             | After Updates | High           | New vulnerabilities                         |

To get the most out of your scans:

- Focus on APIs handling sensitive data.
- Schedule scans during low-traffic times to minimize disruptions.
- Keep a record of vulnerabilities to track patterns over time.
- Regularly update scanning tools to address emerging threats.

Once vulnerabilities are identified, take it a step further by simulating
real-world attack scenarios to test your API's resilience.

### Test Against Attacks

Using the findings from your scans, simulate realistic attacks to expose hidden
weaknesses. The June 2023
[MOVEit Transfer](https://www.progress.com/moveit/moveit-transfer) incident
serves as a stark reminder of the importance of thorough testing. A SQL
injection vulnerability led to widespread data breaches, impacting thousands of
organizations.

Key testing methods include:

- **Dynamic Analysis:** Detect runtime vulnerabilities while the API is in use.
- **Penetration Testing:** Mimic real-world attack scenarios to uncover weak
  spots.
- **Load Testing:** Assess how the API performs under heavy traffic or stress.
- **Fuzzing:** Input malformed or unexpected data to identify breaking points.

Incorporate these security checks early in your development process - a
"shift-left" approach. This strategy helps catch vulnerabilities sooner,
reducing both risks and costs. Modern tools, often powered by AI, enhance
testing by predicting vulnerabilities and automating test case creation, making
the process more efficient.

## Reduce Attack Points

Minimizing your API's attack surface is key to improving security. One effective
way to do this is by decommissioning unused endpoints, which eliminates
potential entry points for attackers and reduces vulnerabilities.

### Remove Unused APIs

Unused API endpoints can become hidden risks. Decommissioning these inactive
endpoints is crucial for maintaining the security of your API. According to
[Azure Policy](https://learn.microsoft.com/en-us/azure/governance/policy/), any
API endpoint that hasn’t received traffic for 30 days is classified as unused
and could present a security threat.

> "As a security best practice, API endpoints that haven't received traffic for
> 30 days are considered unused and should be removed from the Azure API
> Management service. Keeping unused API endpoints may pose a security risk to
> your organization." – Azure Policy

To efficiently manage unused APIs, you can take the following steps:

| **Action**          | **Timeframe** | **Benefits**                        | **Implementation Method**           |
| ------------------- | ------------- | ----------------------------------- | ----------------------------------- |
| API Usage Audit     | Monthly       | Identifies dormant endpoints        | Use automated discovery tools       |
| Endpoint Validation | Bi-weekly     | Confirms which endpoints are active | Change credentials, monitor errors  |
| Version Retirement  | Quarterly     | Reduces exposure to legacy risks    | Follow a phased deprecation plan    |
| Maintain Inventory  | Continuous    | Ensures complete oversight          | Leverage automated tracking systems |

The importance of removing unused APIs is highlighted in the OWASP Top 10 API
Security Vulnerabilities for 2023, where improper asset management is ranked at
number 9 Automated discovery tools can help you maintain a current inventory of
all your API assets, ensuring nothing falls through the cracks.

### Separate Internal APIs

Once dormant endpoints are removed, the next step is to reduce risk further by
isolating internal APIs. This is especially important since internal sources
account for over 60% of data breaches.

To secure internal APIs, create distinct security zones:

- **External Zone**: Public-facing APIs that require heightened monitoring.
- **Internal Zone**: APIs running behind firewalls, accessible only within the
  network.
- **Secure Zone**: APIs handling highly sensitive data, protected with the
  strongest security measures.

For internal APIs, implement these essential security practices:

- Use **multi-factor authentication (MFA)** for all access.
- Set up **role-based access controls** with detailed permissions.
- Ensure data transmission is encrypted with **TLS**.
- Continuously monitor API activity to detect unusual behavior.

> "Internal APIs are the real powerhouse of the API economy." – Karthik
> Krishnaswamy

## Conclusion

API security is an ever-evolving challenge that demands constant attention. With
API attacks increasing each year, implementing strong security measures is
critical to safeguarding both data and system integrity.

A solid API security strategy builds on several key layers:

| **Security Layer**          | **Key Components**                                                  | **Implementation Focus**                 |
| --------------------------- | ------------------------------------------------------------------- | ---------------------------------------- |
| **Authentication & Access** | MFA, API Keys, [JWT tokens](./2025-04-18-jwt-api-authentication.md) | Verifying users and controlling access   |
| **Data Protection**         | HTTPS/TLS, Input validation                                         | Ensuring secure transmission and storage |
| **Traffic Management**      | Rate limiting, Request quotas                                       | Mitigating abuse and DDoS attacks        |
| **Monitoring & Testing**    | Security scans, Penetration testing                                 | Detecting threats proactively            |

APIs now account for more than half of all internet traffic, making them a prime
target for cybercriminals. As noted by [Akamai](https://www.akamai.com/), “APIs
are attractive to hackers because of their potential use in larger data loss”.
This underscores the importance of staying vigilant.

To protect APIs effectively, organizations should:

- **Update security protocols regularly** to address emerging OWASP
  vulnerabilities.
- **Continuously monitor API activity** for unusual or suspicious behavior.
- **Perform routine security audits** to uncover and fix potential weaknesses.
- **Train development teams** on the latest threats and secure coding practices.

Securing APIs isn’t a one-time task - it’s an ongoing process that requires a
combination of technical measures and organizational commitment. By staying
proactive with monitoring, audits, and training, companies can better defend
their APIs against the ever-changing threat landscape.