Zuplo logo
Back to all articles

How to Harden Your API for Better Security

July 18, 2025
20 min read
Nate Totten
Nate TottenCo-founder & CTO

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 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, OpenID Connect, short-lived tokens, and role-based access controls (RBAC).
  • Validate Inputs: Sanitize data to block injection attacks.
  • Limit Requests: Set rate limits 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, 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 and 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 and JWTs while minimizing vulnerabilities.

Set Up API Keys and JWTs#

Properly securing API keys and JSON Web Tokens (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. Here’s how to safeguard API keys:

  • Store keys in environment variables.
  • Use dedicated secrets managers like HashiCorp Vault or AWS Secrets Manager.
  • Employ backend proxy servers to keep keys out of client-side code.

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 (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 TypeAccess LevelTypical Permissions
AdminFullComplete system access
DeveloperElevatedProject and environment management
MemberLimitedBasic 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:

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 TypePurposeRule Example
Data TypeEnsures correct formatInteger: 0-9 only
LengthPrevents buffer overflowString: 2-50 characters
RangeMaintains logical boundsAge: 0-120 years
PatternValidates specific formatsEmail: "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 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 and validate inputs using your docs. Here's how you can do that using Zuplo:

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) 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, 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.

Time WindowQuotaPurpose
Per Second10-50 requestsPrevent rapid-fire attacks
Per Minute100-500 requestsControl bursts of traffic
Per Hour1,000-5,000 requestsManage sustained usage
Per Day10,000-50,000 requestsSet 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 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'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 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 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 LayerImplementationPurpose
Data ClassificationCategorize data by sensitivityIdentify encryption requirements
Storage EncryptionLeverage platform-native toolsSafeguard data at rest
Key ManagementStore keys separatelyProtect encryption keys
Access ControlsApply identity-based permissionsRestrict data access
MonitoringLog activity consistentlyDetect 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 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.
Tweet

Over 10,000 developers trust Zuplo to secure, document, and monetize their APIs

Learn More

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:

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 FeatureSecurity BenefitImplementation Priority
Traffic AnalysisSpot unusual patterns and potential attacksHigh
Request LoggingTrack usage and investigate incidentsHigh
Rate LimitingProtect against DDoS attacks and abuseCritical
Error TrackingIdentify and address vulnerabilitiesMedium

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 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 TypeFrequencyPriority LevelKey Focus Areas
Automated Vulnerability ScansWeeklyHighConfiguration issues, known vulnerabilities
Authenticated ScansQuarterlyCriticalAccess control, data exposure
Full Penetration TestsAnnuallyEssentialComplex attack scenarios
Post-Change ScansAfter UpdatesHighNew 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 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, 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:

ActionTimeframeBenefitsImplementation Method
API Usage AuditMonthlyIdentifies dormant endpointsUse automated discovery tools
Endpoint ValidationBi-weeklyConfirms which endpoints are activeChange credentials, monitor errors
Version RetirementQuarterlyReduces exposure to legacy risksFollow a phased deprecation plan
Maintain InventoryContinuousEnsures complete oversightLeverage 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 LayerKey ComponentsImplementation Focus
Authentication & AccessMFA, API Keys, JWT tokensVerifying users and controlling access
Data ProtectionHTTPS/TLS, Input validationEnsuring secure transmission and storage
Traffic ManagementRate limiting, Request quotasMitigating abuse and DDoS attacks
Monitoring & TestingSecurity scans, Penetration testingDetecting threats proactively

APIs now account for more than half of all internet traffic, making them a prime target for cybercriminals. As noted by Akamai, “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.

FAQs#

What’s the difference between OAuth 2.0 and OpenID Connect, and how do they improve API security?#

OAuth 2.0 and OpenID Connect are often mentioned together, but they serve different roles in API security.

OAuth 2.0 is all about authorization. It allows third-party apps to access a user’s resources without needing the user’s credentials. Instead, it uses access tokens to define and enforce specific permissions. What it doesn’t do, though, is confirm who the user actually is.

That’s where OpenID Connect (OIDC) steps in. Built on top of OAuth 2.0, OIDC adds authentication to the mix. It introduces an ID token that verifies the user’s identity, making it possible to implement features like Single Sign-On (SSO). This simplifies things for users by reducing the need to log in repeatedly across different apps, while also enhancing security.

By combining scoped access tokens for limited permissions with secure data transmission protocols like TLS, both OAuth 2.0 and OIDC work together to create a strong framework for managing access and confirming identities in today’s API-driven world.

How can API gateways help secure and manage API traffic effectively?#

API gateways play a key role in securing APIs and managing traffic effectively. One major feature they provide is rate limiting, which sets a cap on how many requests a user or application can make within a specific time. This not only helps prevent misuse, like denial-of-service (DoS) attacks, but also ensures fair access for all users.

Another critical function of API gateways is centralizing authentication and authorization. This ensures that security policies are applied consistently across every API. On top of that, they keep an eye on traffic in real-time, identifying and blocking suspicious behaviors, such as potential DDoS attacks. Together, these features make API gateways essential for maintaining a secure and dependable API environment.

What are the most common API input validation vulnerabilities, and how can you prevent them?#

APIs often face risks from weak input validation and poor error handling, both of which can open the door to threats like SQL injection or unintentionally exposing sensitive data. To counter these risks, it's crucial to implement strict input validation. This means checking not only the format of the input (syntactic validation) but also its intended purpose (semantic validation). Additionally, sanitizing inputs and encoding outputs are essential steps to block malicious code execution.

To bolster security further, consider incorporating tools like Web Application Firewalls (WAFs) and conducting regular security tests. These measures help make your API more resistant to attacks and provide stronger protection for user data.