Engineering
April 10, 2024
9 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 we launch a web page or an app on our 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 (that is: 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.

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.

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.

Common 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.

Managing security risks and threats

“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. (We may 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.

Authenticate and authorize

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.

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.

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.

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.

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.