Engineering
August 12, 2024
12 min read

Keeping Your APIs Safe: Best Practices for Top-Notch Security

Paul Vergilis

Application programming interfaces (APIs) are everywhere, and they play a role in running nearly everything in our digital-centric lives. Each time you launch a web page or an app on your phone, dozens of API calls are happening in the background to render an experience heavily customized to you. Increasingly, even the everyday items in your home are talking to APIs — from smart speakers like Amazon Echo to appliances, electricity meters, and lightbulbs.

But as the use of APIs continues to grow, so does the need for API security.

Businesses are increasingly relying on APIs to enable seamless integration with partners, vendors, and third-party applications, and API security breaches can result in serious financial and reputational damage to an organization — with some API security research placing the average cost per attack at around $6.1 million.

APIs are now the leading vector used by malevolent actors (think: cyber criminals, not Willem Dafoe) to steal data, disrupt operations, conduct fraud, and partake in a slew of other sinister activities that are bad news for businesses.

With APIs becoming fundamental to modern app development, the attack surface — all entry points through which an attacker could potentially gain unauthorized access to a network or system to extract or enter data or to carry out other malicious activities — is continually increasing. The solution? API security.

What is API security?

API security is a set of best practices aimed at protecting an organization’s APIs. Apart from the infrastructural security parameters, companies should also secure APIs programmatically at the application logic level.

Appropriate API permissions and rules should be in place to ensure that only the desired audience consumes the right kind of permissible APIs.

API security is an essential component of any modern digital enterprise. With the right security measures in place, businesses can ensure their APIs are secure and that the sensitive data they transmit is protected from unauthorized access.

Expanding on API Security Measures

In addition to the basic definition, API security encompasses:

  1. Authentication and authorization: Implementing robust systems to verify the identity of users and applications accessing the API, and controlling what resources they can access.
  2. Encryption: Ensuring that all data transmitted through APIs is encrypted, both in transit and at rest.
  3. Rate limiting: Implementing controls to prevent abuse of APIs through excessive requests.
  4. Input validation: Carefully validating and sanitizing all input to prevent injection attacks and other vulnerabilities.
  5. Monitoring and logging: Continuously monitoring API traffic for suspicious activity and maintaining detailed logs for auditing and incident response.

Why API security is important

Since the software industry is widely dependent on APIs, it’s necessary for organizations that provide them to make them more secure and trustworthy. At API Summit 2023, Ahmed Koshok and Tyler Reynolds — Senior Solution Architect at Kong and Channel & GTM Director at Traceable.ai — discussed the increasing importance of API security and its best practices.

“We’re certainly in the early days of this emerging API security space,” Reynolds said. “But in thinking about API security going forward, it’s going to become the very foundation for modern applications.”

APIs are used to access sensitive information, including personally identifiable information (PII), financial data, and intellectual property. Currently, 90% of web traffic is flowing through some kind of API, and much of this traffic carries sensitive data. Any unauthorized access or data breaches can lead to severe consequences for an organization, including legal liabilities, loss of customer trust, and reputational damage. Additionally, many industries are subject to regulatory requirements regarding the protection of sensitive data.

An API security strategy can help organizations comply with these regulations, avoid penalties, and maintain their reputation.

“We can’t afford not to address this problem head-on,” Reynolds said.

Additional reasons for API security importance

  1. Increasing sophistication of attacks: Cybercriminals are continuously developing more advanced techniques to exploit API vulnerabilities. As APIs become more complex, so do the potential attack vectors.
  2. Business continuity: API breaches can lead to service disruptions, affecting not just the organization but also its partners and customers who rely on these APIs for their operations.
  3. Competitive advantage: Strong API security can be a differentiator in the market, especially for businesses handling sensitive data or operating in regulated industries.
  4. Cost efficiency: Implementing robust API security from the start is more cost-effective than dealing with the aftermath of a security breach.

Identifying and managing API security risks

Identifying and managing API security risks is a critical aspect of maintaining a secure and reliable API infrastructure. 

Here are some steps organizations can take to minimize API security risks.

  • Inventory and manage your APIs. Whether an organization has a dozen or hundreds of publicly available APIs, it must first be aware of them to properly secure and manage them. API sprawl and governance are prevalent problems across all clouds and legacy infrastructure, and nobody can secure what they don’t know or understand. Therefore, it’s essential to record all APIs in a registry to define characteristics (such as name, purpose, payload, usage, access, live date, retired date, and owner). This will avoid shadow or silo APIs that were forgotten, never documented, or developed outside of a main project — possibly through mergers, acquisitions, or test or deprecated versions.
  • Monitor and log API activity. Monitoring and logging API activity is an essential aspect of identifying potential security risks. Attackers often probe an API repeatedly to find vulnerabilities or logic they can exploit, so real-time monitoring is essential for attack detection and response. This approach requires no predefined policies, rules, or attack signatures, so it will always be able to adapt to new and evolving attacks.

“The two dimensions of API management are the knowledge of the existence of the API and the application of API governance on it. Ideally, all APIs should be known and managed,” Koshok said.

Once an organization takes stock of its APIs, Kong helps it develop a 360 API security management framework to understand those APIs, usage patterns, dependencies and application flows, and risk levels for every endpoint.

Steps for managing API security risks

  1. Regular security audits: Conduct periodic security audits of your APIs to identify potential vulnerabilities and ensure compliance with security policies.
  2. Penetration testing: Employ ethical hackers or use automated tools to perform penetration testing on your APIs, simulating real-world attack scenarios.
  3. API versioning: Implement a robust API versioning strategy to manage changes and updates without disrupting existing integrations or introducing new vulnerabilities.
  4. Developer education: Provide ongoing education and training for developers on API security best practices and emerging threats.
  5. Incident response plan: Develop and regularly update an incident response plan specifically for API-related security incidents.

Common API security risks

There are several common API security risks that organizations should be aware of when implementing APIs, like those found in the OWASP API Security Top 10 list.

Poor or non-existent authentication and authorization are major issues with many publicly available APIs. Broken authentication occurs when APIs do not enforce authentication (as is often the case with private APIs, which are meant for internal use only) or when an authentication factor (something the client knows, has, or is) can be broken into easily. Since APIs often provide an entry point to an organization's databases, it's critical that the organization strictly controls access to them.

APIs are susceptible to many of the same kinds of attacks defenders have been fighting in their networks and web-based apps for years. None of the following attacks are new, but they can easily be used against APIs.

  • Injection occurs when an attacker is able to insert malicious code or commands into a program, usually where ordinary user input (such as a username or password) is expected. SQL injection is a specific type of injection attack, enabling an attacker to gain control of an SQL database.
  • Cross-site scripting (XSS) is a type of injection attack that occurs when a vulnerability enables an attacker to insert a malicious script (often JavaScript) into the code of a web app or webpage.
  • Distributed denial-of-service (DDoS) attacks make a network, system, or website unavailable to intended users, typically by flooding it with more traffic than it can handle. API endpoints are among the growing list of DDoS targets.
  • Man-in-the-middle (MitM) attacks occur when an attacker intercepts traffic between two communicating systems and impersonates each to the other, acting as an invisible proxy between the two. With APIs, MitM attacks can occur between the client (app) and the API, or between the API and its service.

Insufficient encryption can result in data breaches and other security incidents. This includes using weak encryption algorithms, failing to encrypt sensitive data, and not implementing SSL/TLS encryption to protect data in transit.

Protect Mission-Critical APIs & Services: Efficient protection strategies revealed

Emerging API security risks

In addition to the common risks mentioned above, several emerging threats are becoming more prevalent in the API security landscape:

  1. API abuse and misuse: Attackers may use legitimate API functionalities in unintended ways to extract sensitive data or overwhelm systems.
  2. Broken object level authorization (BOLA): This occurs when an API doesn' properly check that a user has permission to access specific objects, allowing attackers to view or manipulate data they shouldn't have access to.
  3. API parameter tampering: Manipulating API parameters to bypass security controls or access unauthorized data.
  4. API schema poisoning: Attackers may manipulate API documentation (like OpenAPI/Swagger files) to mislead developers and potentially introduce vulnerabilities.
  5. Improper assets management: Failing to properly inventory and manage all API endpoints, including deprecated versions, can lead to vulnerabilities.

Protect mission-critical APIs and services: Efficient protection strategies revealed

“The scary thing about these breaches is that the exploited APIs worked exactly as they were designed,” Reynolds shared. “It’s not about a bug in the code — it’s about simply leveraging the predictable nature of an API against itself to make it do something the developer didn’t intend.”

That’s why no matter how sound your APIs are, you need to prioritize security. (Not to sound like a broken record, but this step is easy to neglect.) API security shouldn't be an afterthought or deemed someone else's problem. Organizations have a lot to lose with unsecured APIs, so build security into your APIs as they're being developed and implement a strong management system.

Reynolds continued, “API security is really a big data problem. For a comprehensive API security approach, you must have awareness of data and identities and intimately understand the business logic of an application end-to-end.”

One of the most critical aspects of API security is implementing authentication and authorization. This step ensures that only authorized users can access the API, and their access levels are appropriate for their role. When feasible, use solutions based on solid, proven authentication and authorization mechanisms, such as OAuth2.0 and OpenID Connect.

API authentication and authorization 

API authentication and authorization refer to the processes of verifying the identity of a client and controlling access to API resources. Authentication is verifying who the client is and authorization is controlling what they can access after being authenticated.

Proper API security requires implementing both authentication and robust authorization controls. To control access to API resources, you must carefully and comprehensively identify all related users and devices. This typically requires client-side applications to include a token in the API call so that the service can validate the client.

Use standards such as OAuth 2.0, OpenID Connect, and JSON web tokens (JWTs) to authenticate API traffic and to define access control rules or grant types that determine which users, groups and roles can access specific API resources.

Advanced authentication and authorization techniques

  1. Multi-factor authentication (MFA): Implement MFA for accessing sensitive API endpoints to add an extra layer of security.
  2. Fine-grained access control: Use attribute-based access control (ABAC) or role-based access control (RBAC) to provide more granular control over API resource access.
  3. Token lifecycle management: Implement proper token lifecycle management, including token revocation and refresh mechanisms.
  4. API keys vs. tokens: Understand the difference between API keys and tokens, and use them appropriately based on the security requirements of your API.
  5. Continuous Authentication: Implement systems that continuously verify the authenticity of API requests throughout a session, not just at the initial point of access.

Consistency across security models

Being consistent in applying security models to APIs, both internal and external facing, helps ensure that all APIs have proper authentication and authorization in place. This reduces the risk that an API could be accessed without the proper credentials or permissions. Using consistent models also makes it easier to audit and validate that security controls are properly implemented across all APIs.

If different models are used, it increases the complexity of managing API security overall. With a consistent approach, changes to security mechanisms only need to be applied in one place rather than re-implemented separately for different APIs.

Overall, consistency enables better policy enforcement, lowers the chance of misconfiguration, and makes it simpler to maintain API security at scale as more APIs are added.

Strategies for maintaining consistency

  1. Centralized policy management: Use a centralized system for managing and enforcing security policies across all APIs.
  2. API security frameworks: Adopt or develop an API security framework that can be consistently applied across your organization.
  3. Automated security testing: Implement automated security testing as part of your CI/CD pipeline to ensure consistent security practices across all APIs.
  4. Regular security reviews: Conduct regular security reviews to ensure that all APIs adhere to the organization's security standards and best practices.
  5. API governance: Establish a strong API governance program that includes security as a key component, ensuring consistency in security practices across the API lifecycle.

Establishing secure communication

Using encryption

All network traffic should be encrypted — particularly API requests and responses, as they’ll likely contain sensitive credentials and data. All APIs should use and require HTTPS. Enabling HTTP Strict Transport Security where possible is better than redirecting HTTP traffic to HTTPS, as API clients may not behave as expected.

Advanced encryption strategies

  1. Perfect forward secrecy: Implement perfect forward secrecy to ensure that session keys will not be compromised even if the server's private key is compromised.
  2. Certificate pinning: Use certificate pinning to prevent man-in-the-middle attacks by ensuring that a client only connects to a server with a specific certificate.
  3. Mutual TLS (mTLS): Implement mutual TLS for sensitive APIs to ensure both the client and server authenticate each other.
  4. Quantum-safe cryptography: Start planning for the implementation of quantum-safe cryptographic algorithms to protect against future quantum computing threats.

Implementing access control

The first step in implementing API access control is to identify the resources that you want to control access to. This could be specific endpoints, data resources, or operations within the API.
Organizations that want to enable third parties to access internal data and systems through APIs must introduce and test controls to manage that access: who, what, and when, as well as checks on data access, creation, update, and deletion — the zero-trust security model.

Advanced access control techniques

  1. Context-aware access control: Implement access controls that take into account factors such as user location, device type, and time of access.
  2. Least privilege principle: Apply the principle of least privilege, granting users only the minimum level of access necessary to perform their tasks.
  3. Dynamic authorization: Implement dynamic authorization systems that can make real-time access decisions based on various factors and policies.
  4. API throttling: Implement API throttling to limit the rate at which a user can make requests, preventing abuse and ensuring fair usage.

Maintaining data integrity

Maintaining API data integrity is crucial to ensure that the data transmitted through your API is accurate, complete, and consistent.

Validating inputs

Never assume API data has been cleansed or validated correctly. Implement your own data cleaning and validation routines server side to prevent standard injection flaws and cross-site request forgery attacks. Debugging tools can help examine the API’s data flow and track errors and anomalies.

Wrapping error responses

Wrapping error responses from APIs prevents sensitive implementation details from being exposed in the client-facing response.

For example, by returning a generic "404 Not Found" response instead of a framework-specific error message, the underlying technology stack remains opaque. This helps avoid inadvertent information disclosure that could aid an attacker. Wrapping also provides a consistent error response format for clients, regardless of the actual error that occurred. The client gets actionable information to handle errors gracefully rather than parsing unexpected server error messages.

Most importantly, error wrapping enables APIs to comply with fail-safe defaults where you assume requests will fail and plan accordingly. APIs can validate data integrity before responding rather than exposing partial or corrupt internal state via unwrapped errors. Overall, wrapping API error responses improves security, reliability, and clarity of communication for API consumers.

Share only necessary information

Some APIs reveal far too much information, whether it's the volume of extraneous data that's returned through the API or information that reveals too much about the API endpoint. This typically occurs when an API leaves the task of filtering data to the user interface instead of the endpoint. Ensure that APIs only return as much information as is necessary to fulfill their function. In addition, enforce data access controls at the API level, monitor data, and obfuscate if the response contains confidential data.

Remove information that's not meant to be shared. Because APIs are essentially a developer's tool, they often contain keys, passwords, and other information that should be removed before they're made publicly available. But sometimes this step is overlooked. Organizations should incorporate scanning tools into their DevSecOps processes to limit accidental exposure of secret information.

Conclusion

APIs create countless opportunities for organizations to improve and deliver services, engage customers, and increase productivity and profits — but only if you securely implement them. When you’re building an API, think about quality and security during development, instead of waiting until after the fact. A secure API is a good API!

Want a deeper dive into ensuring API security best practices in your organization? Check out our eBook Leading Digital Transformation: Best Practices for Becoming a Secure API-First Company.

Developer agility meets compliance and security. Discover how Kong can help you become an API-first company.