8 API Security Best Practices

Goal: Getstream.io sells secure in-app chat and feeds APIs. App owners and product managers are their key ICPs. The client wanted me to write a blog about useful and actionable API security principles.

Approach: In Jan 2023, OWASP had just released data on the top 10 API security risks. I used these risks as my problem statement and researched possible solutions/ recommendations for each API security risk. I provided actionable directives and flipped the problems to solution-based headers. I increased the stakes by opening and closing this blog with a big (recent) API attack story – to show how costly inadequate API security can be.

Result: The piece initially had a healthy ‘time-on-page’ metric. However, due to various internal team changes, we failed to actively distribute this blog, so we couldn’t convert the initial organic traffic into better outcomes. I include this in my portfolio because, over the following years, many ‘similar thinking’ writers (including the top-performing SERPs) adopted this structure and form to explain ‘API security best practices’. It also serves as a reminder about how distribution is critical to content performance.

Note: I ghost-wrote this piece for the GetStream blog.


In September 2022, nearly 10 million customer records were stolen from Optus, a leading Australian telco. The stolen data included customer names, contact details, passport numbers, and medical information.

The company attributed the data breach to a sophisticated cyberattack, but further investigation reports revealed that Optus used an API that “did not require authorization or authentication.” In hindsight, any developer could have used that vulnerable Optus API to access sensitive customer records.

Application programming interfaces (APIs) offer greater flexibility, cost-effectiveness, and rapid development options because they allow you and your users to reuse external software services and data flows. However, inadequate API security will attract attacks.

Before we examine API security best practices to prevent Optus-like attacks, let’s review the basics and how they differ from app security.

API Security Protects Sensitive Data From Bad Actors

API security measures such as authentication, authorization, encryption, and monitoring can greatly mitigate unauthorized access.

Authentication is the process of questioning and validating the credibility of a user’s identity. After user authentication, APIs must also determine the level of resources every user can access. Typically, a combination of secret keys, protocols like OAuth 2.0JSON web tokens (JWT), or HTTP headers is used to authenticate API users and validate their authorization levels.

API encryption provides an additional layer of security by converting plain data into an unreadable cipher that can be unlocked only with a valid key. However, even after implementing API security measures, the possibility of an attack still exists. A monitoring system will help you detect any API usage anomalies and reduce the risk of an undetected attack.

The top two API security risks according to OWASP are:

1. Broken Object Level Authorization — Failing to validate user inputs or permissions before granting access to an object

2. Broken User Authentication — Vulnerabilities that allow attackers to impersonate legitimate users

    API Security Differs From App Security

    APIs are built to connect different applications and systems, so they are infinitely extendable. However, extendibility creates fuzzy boundaries and unknown access points. So, API security requires additional discovery, testing, monitoring, and active runtime protection capabilities beyond what conventional web apps require.

    In addition to having more access points, APIs are more flexible regarding changes. For instance, an API can have more than one version in production. So, an API creator can choose to make a new API version available to new subscribers, even as existing users continue using its older version. These multiple API versions can sometimes cause security problems that a conventional web application firewall (WAF) might not detect.

    On a similar note, APIs can also adapt to different software environments. For example, an API in PHP can deliver a JSON or XML payload that can be used by an application in JavaScript. Again, this adaptability can pose new cybersecurity threats that don’t exist in web applications.

    So, in order to bolster API security, you need to:

    1. Discover all your APIs: Tools such as Google Discovery or Postman automate the discovery of all your API endpoints. This is the first step toward identifying API security risks and gaps.

    2. Assess your existing level of API protection: Determine how secure your API gateway is and understand if you need to augment your WAF with Web App and API Protection (WAAP).

    3. Employ an API monitoring system: Detect behavioral anomalies and understand what’s causing those pesky 4XX problems using tools such as Prometheus or Graphite.

    4. Perform API security tests: Uncover hidden security risks by testing your business logic and current API usage practices.

      8 API Security Best Practices 

      Bad actors employ brute force, credential stuffing, and distributed denial-of-service (DDOS) attacks to access API keys and sensitive data. So, you need to employ a combination of the following eight API security best practices.

      1. Authenticate Users

      Use the OAuth protocol to standardize the authentication of API users and sessions. By asking for user credentials in only one place, OAuth lowers the risk of exposing user credentials to bad actors and helps you set customized API resource access rules.

      Consider using OpenID Connect on top of the OAuth protocol for an added layer of authentication security. OpenID relieves you from the responsibility of managing end-user credentials. It offers granular ‌access control features and provides your end users with features such as encryption of identity data, discovery of OpenID Providers, and a predefined logout option. It also allows web, mobile, and JavaScript clients to ask or get information about authenticated users or sessions.

      Using SAML to authenticate your API end users from a secure identity provider they already use is also a smart way to offer single sign-on (SSO).

      Combining these three authentication methods helps you validate user identity and sessions to prevent API identification and authentication failures.

      As a result, your API will:

      – Be more resilient to credential-stuffing attacks

      – Discourage users from reusing weak passwords 

      – Avoid inadequate session timeout settings

      2. Implement Authorization Checks

      After authenticating your API users, you must determine their access levels.

      We recommend giving users the least privilege, resources, and data they need to perform tasks. For example, a user from customer support may use your API to access support tickets, but they shouldn’t have access to users’ personally identifiable information (PII). This allows you to reduce your attack surface and minimize security threats from excessive data exposure.

      Inadequate authorization checks will be exploited to make legitimate-looking unauthorized API calls. For instance, users with ‘read-only’ permission to read records may attempt to write new records by changing your API’s HTTP method from GET to PUT. Implement the right level of authorization checks to avoid such broken function-level authorization threats.

      3. Encrypt API Requests and Responses

      Encrypting all data transfers between the API server and the client helps you mitigate risks from snooping or man-in-the-middle attacks. Encrypt REST APIs that use HTTP with either a Transport Layer Security (TLS) or a Secure Sockets Layer (SSL) protocol.

      Either of these two protocols can effectively encrypt data in motion. However, you’ll still need a WAAP to protect data at rest behind an API.

      4. Manage API Keys Effectively

      API keys provide users a secure way to access resources and data from the API server. The following steps will help you manage API keys and prevent threats from improper asset management.

      – Generate unique random keys that make it impossible for bad actors to guess any patterns

      – Define granular resource access rights for each user’s API key

      – Store the API keys as hashed values and not as plain text

      – Delete the API keys that have little or no API traffic

      5. Use Rate Limiting and Throttling

      OWASP highlights that it is common for APIs to allow requests without limitations. Bad actors can exploit such APIs by automatically executing multiple concurrent API requests. The overwhelming number of requests can eventually lead to denial-of-service (DoS) or make the API unresponsive. 

      APIs must implement rate limits and throttle resource requests exceeding a predefined quota. A good practice is to define limits for:

      – Memory

      – CPU

      – Number of restarts

      – How frequently a user can place requests 

      6. Validate All API Resource Requests

      An API gateway can help you protect API resources from unauthorized requests and malicious code injections by validating user identity and providing temporary time-bound tokens.

      An API gateway helps users request API resources using identity data from their smartphones without sharing usernames or passwords. This allows you to limit API resource usage for each validated user identity.

      7. Monitor API Usage

      Monitoring API activity helps you detect anomalies that might be attacks. Monitoring also gives information to trace how bad actors exploited your API.

      Insufficient monitoring systems give bad actors the time they need to access API resources without detection. Imagine a web application being hit with a credential-stuffing attack, triggering thousands of failed login alerts. Without a monitoring system, the security team won’t be alerted to this threat unless someone periodically looks at the login logs.

      8. Test for API Security Risks

      Routine API security testing will help you spot security misconfigurations and uncover hidden business logic flaws that may lead to compromised data.

      Security teams can eliminate mass assignment threats by periodically testing for vulnerabilities that bad actors can exploit.

      Manual API Security Testing Methods

      The OWASP API Security Top 10 list provides a good framework for testing. Combine the following manual security testing methods to detect vulnerabilities in your internal APIs.

      Test Parameter Tampering

      Hackers can tamper with parameters sent through APIs and gain unauthorized access to sensitive information. For example, an attacker can modify hidden form fields of an ecommerce website and buy products for a lower price.

      To avoid such unauthorized actions, test your business logic, user workflows, and the accidental presence of hidden field information.

      Test Command Injection

      Bad actors can execute unauthorized operating system-level commands by injecting malicious code via forms, cookies, HTTP headers, URL changes, and SQL injections. For example, an attacker can create a wrapper around the UNIX command and inject it via an HTTP header.

      Test if your API allows the injection of an operating system command, like a system reboot. And take the necessary actions to secure your API from such command injections. 

      Test HTTP Methods

      Bad actors can use various HTTP methods to store, delete, or retrieve data without adequate permissions. So, APIs that support HTTP methods on the server side are vulnerable to such attacks. For example, a bad actor can modify a GET method to a PUT or POST method.

      To avoid this, test your API server to see if it allows the modification of HTTP methods. If it does, secure it.

      Use Only Secure, Encrypted, and Compliant APIs

      Australian Home Affairs Minister Clare O’Neil went on air and blamed Optus, saying they “effectively left the window open for data of this nature to be stolen.” However, companies like Optus aren’t the only ones vulnerable. API attacks cost businesses $75 billion annually. Furthermore, ineffective API security causes bad press, reputational harm, and distrust of your users.

      So, protect your APIs with adequate security and encryption capabilities to avoid such API security risks.

      Also, only select APIs that meet your business needs, such as GDPR or HIPAA compliance. For instance, if you’re looking to use a chat API or activity feed API, you must factor in security and compliance.