Top 12 API security best practices you need to know
Why API security should be a top priority for your company
An Application Programming Interface (API) serves as the bridge that enables software systems to interact and exchange data with one another. Because APIs are ubiquitous as fundamental components in modern software applications, they are a tempting target for cyber attackers. If you build software applications, you likely use and develop APIs. Therefore, API security must be a top priority.
In this post, we’ll look at API security. We’ll look at why APIs are at risk, some of the most common API security risks, best practices to help keep your APIs secure, and some types of API testing. Let’s dive in.
What is API security?
API security refers to the practices and protocols put in place to protect APIs (Application Programming Interfaces) from being misused or attacked. This involves ensuring that only authorized users, systems, or applications have access to the API and that the data exchanged through the API is protected against unauthorized access, alterations, or theft. API security encompasses various aspects that aim to:
Verify the identities of users and applications accessing the API.
Restrict access to specific resources and functionalities based on user permissions.
Securely transmit data between the API and its users.
Detect and prevent unauthorized access, data breaches, and other malicious activity.
Why is API security important? The necessity of appropriate security controls
Cyber attackers target APIs because APIs are everywhere. APIs are the front door to software applications. If attackers can exploit an unsecured API, then they may be able to interact with the systems, networks, and data that those software applications access.
The below graph shows data compromises, records exposed, and users impacted:
A successful attack on an API can lead to any of the following consequences:
Data breaches that expose sensitive information
When an API is compromised, it can lead to unauthorized access to sensitive data such as personal information, financial details, and confidential business data. For businesses, a data breach can result in legal consequences, including hefty fines and sanctions, especially if the breach violates data protection regulations like GDPR or HIPAA.
A system outage
An API attack, such as a Denial of Service (DoS) or Distributed Denial of Service (DDoS), can overwhelm the system, leading to outages. Prolonged outages can lead to significant revenue loss, contractual penalties, and resource expenditure in efforts to restore services.
Loss of customer trust
Customers expect their data to be handled securely. A breach or any security incident can erode their trust. Rebuilding customer trust is a long and challenging process, often requiring substantial investments in security improvements and public relations efforts.
Damaged business reputation
News of a security breach can spread rapidly, damaging the company's public image and brand reputation. Recovery from reputational damage is often more challenging than addressing the financial implications of a breach, as it affects customer perception and market position in the long term.
Significant financial losses
The financial impact of an API attack encompasses direct and indirect costs. For some businesses, especially small and medium-sized enterprises, the financial burden of a major security incident can be crippling, potentially leading to business closure.
Noteworthy API security incidents
To make this more concrete, consider these two (among many in recent history) noteworthy incidents that resulted from insecure APIs:
Peloton (2021): It was discovered that APIs from Peloton, a maker of exercise equipment and provider of subscription-based fitness services, would respond to unauthorized requests by returning user data that included personally identifiable information (PII). The data privacy impact for Peloton customers cannot be understated.
Twitter (2022): Cybercriminals began selling user data from over 5 million Twitter users, after exploiting an API vulnerability that exposed Twitter account information when an existing email address or phone number was submitted for a query.
As seen in the graph above, the exploitation of unsecured APIs by cyber attackers is on the rise. In 2022, the United States alone saw over 1,800 data compromises, with the total number of individuals impacted estimated to be over 400 million. Compare this with the numbers from 10 years prior, in which the United States saw less than 500 data compromises impacting less than 20 million individuals.
Fortunately, software developers are not powerless when facing these challenges. Their first step is to become familiar with common web API security risks.
5 common API security risks and how to mitigate them: How to protect sensitive data
The OWASP API Security Top 10 is a list of the most common API vulnerabilities and security risks. By familiarizing yourself with this list and mitigation strategies for each item, you’ll make significant strides in securing your APIs. We’ll highlight three items from the list.
1. Broken object level authorization
In this vulnerability, an API endpoint does not properly enforce authorization, potentially exposing data to someone who is not authorized to access it.
For example, imagine you are logged into an e-commerce web application, and you are viewing your order history. In your browser’s developer tools, you notice that the order history page sends a request to https://api.techgear.biz/users/1439/orders. On a whim, you send a curl request to https://api.techgear.biz/users/1440/orders, and you’re surprised to see the order history for another customer. It appears that this order history API endpoint suffers from broken object level authorization.
Addressing this vulnerability means implementing authorization measures—verifying that the person requesting the resource is authorized to access it—for every API endpoint that is not intended to be public.
2. Broken or stolen authentication
If the authentication mechanism of an API is vulnerable and can be exploited, then an attacker can gain access to protected API endpoints as purportedly authenticated users. Examples of broken authentication include:
Allowing repeated (and unlimited) attempts from the same requester to log in, even after multiple unsuccessful logins. This gives attackers an opportunity to brute-force log in.
Honoring a request to change an account password without requiring any confirmation of identity (such as clicking a unique link in an email associated with that account).
Broken authentication can be mitigated by employing techniques like rate limiting or locking an account after a certain number of failed login attempts.
3. Man-in-the-middle attack
A Man-in-the-middle (MitM) attack is a form of cyber eavesdropping where the attacker secretly intercepts and possibly alters the communication between two parties who believe they are directly communicating with each other. The goal of a MitM attack can vary from eavesdropping on communications, and stealing sensitive data, to injecting malicious content into the communication stream.
By adopting robust encryption, verifying server certificates, and choosing secure protocols like HTTPS, you create a digital fortress, making it difficult for anyone to eavesdrop or tamper with your online interactions. Additionally, staying vigilant about software updates, avoiding insecure Wi-Fi networks, and employing comprehensive security solutions further empower you to combat these unseen threats.
4. Code injections
A code injection is a type of cyber attack where an attacker exploits a vulnerability in a software application to introduce and execute malicious code. This code is typically inserted into a program or system through input fields or data entry points that do not properly sanitize or validate the input. The injected code can then be executed by the system, leading to various harmful outcomes, such as data theft, data corruption, loss of system control, and other security breaches. An SQL injection, cross-site scripting (XSS), command injection, and HTML injection are all examples of a code injection.
Protecting your code from a malicious data injection requires a multi-layered approach. Rigorously sanitizing all user input before processing it removes potential hiding places for harmful code. Employing parameterized queries instead of string concatenation specifically addresses the threat of SQL injection. Additionally, encoding output before sending it back to the user prevents malicious scripts from wreaking havoc. Consider web application firewalls (WAFs) as your digital sentinels, constantly on guard against common attack patterns. Finally, remember that software updates are not just routine, they are shields: patch vulnerabilities promptly to ensure your code remains a fortress against malicious intrusions.
5. Unrestricted resource consumption in a DoS attack
In this vulnerability, an API honors and responds to multiple requests from the same requester without limit. Because APIs require resources such as CPU, memory, and network bandwidth, an attacker can exploit this vulnerability and automate sending a flood of requests to the API (a denial of service or DoS attack). The drain on resources will impact the API’s service rate, potentially taking it down entirely.
Techniques for mitigating this risk include implementing request limits, defining and enforcing the maximum size of request payload data, and rate limiting.
For a deep dive on these risks and the rest of the list, read up on the OWASP top 10 security vulnerabilities.
OWASP top 10 security vulnerabilities
OWASP API Security Top 10
Top 12 API security best practices
With these API risks in mind, developers can adopt certain practices to enhance the security posture of their APIs, implement robust security controls, and overall make their web applications less susceptible to potential threats. Let’s consider the top five API security best practices.
1. Implement authentication and authorization
Four out of the 10 vulnerabilities from the OWASP top 10 list directly relate to broken authentication or authorization mechanisms. To prevent unauthorized access to your APIs (and the data fetched by your APIs), implementing robust authentication and authorization is essential.
When implementing authentication and authorization, leverage existing libraries and packages if at all possible. This is not an area where you should “roll your own”, but instead should trust the expertise and experience of the open source developer community. Consider implementing two-factor authentication (2FA) to give your application an extra layer of security. This is critical for businesses and consumers.
2. Perform input validation
Not all malicious users are unauthorized users. Some have proper credentials to interact with your APIs, but they use that access to test your APIs for exploitable vulnerabilities, often by manipulating the data payloads and query parameters that serve as inputs to an API request. This is why input validation is important for API security.
A good rule of thumb for implementing input validation is to assume that all user inputs are dangerous. Given this assumption, you should sanitize and validate all user inputs, preparing them for safe handling before you accept them for processing.
3. Enforce appropriate limits: Implement rate limiting
Denial of service (DoS) and distributed denial of service (DDoS) attacks on APIs are common. Rate limiting, now a common feature built into API gateway and load balancing services, can protect your APIs from these kinds of attacks.
In addition, consider and implement other kinds of limits to protect your APIs from abuse. For example:
Limit the number of failed login attempts for an account. When that number is exceeded, lock the account or force a wait before the next attempt.
Limit the size of the data payload that can be sent with a request. This includes JSON, which is the typical form of data used when making an API request, but also includes file uploads.
Limit spend controls for third-party services that your APIs may request. Abuse of an API endpoint may lead to a spike in service costs incurred by your API.
4. Use SSL (Secure Socket Layer) or TLS (Transport Layer Security) encryption
Using SSL/TLS encryption is a fundamental best practice for API security due to several critical reasons. Firstly, SSL/TLS establishes a secure and encrypted channel over the internet, ensuring that data transferred between the client and the server is protected from eavesdropping and tampering. This is particularly important for APIs, as they often handle sensitive data, including personal information, financial details, and authentication credentials. Secondly, SSL/TLS provides authentication, verifying that the server the client is connecting to is indeed the correct one, thereby preventing Man-in-the-Middle (MitM) attacks. This authentication is achieved through the use of digital certificates issued by trusted certificate authorities. Additionally, SSL/TLS helps in maintaining data integrity, ensuring that the data sent and received has not been altered or corrupted during transmission. In the context of regulatory compliance, using SSL/TLS is often a requirement to meet data protection standards like GDPR, HIPAA, and PCI DSS.
5. Implement secure error handling
OWASP warns us of the dangers of improper error handling. Error messages are often meant to be helpful for developers who use them for debugging purposes. However, error messages with too much detail may inadvertently expose API implementation information that can be exploited by attackers. Use standard and consistent error messages, taking care not to expose excessive detail.
For example, consider a login page for a web application. On one failed attempt to log in, the returned error message is “The password is incorrect.” On a separate failed attempt, the returned message is “User with this email could not be found.” This inconsistency in error messaging inadvertently exposes (in the first message) that a user with the given email address does exist in the system.
6. Use proper auditing and logging practices
Auditing and logging are best practices in API security for several key reasons. Firstly, they provide visibility into API usage and activities, allowing you to monitor normal and anomalous behavior. This visibility is essential for detecting potential security incidents, such as unauthorized access attempts or unusual patterns of use that could indicate a breach or an attack in progress. Secondly, detailed logs are invaluable for forensic analysis in the event of a security incident. They enable organizations to trace the source of an attack, understand its impact, and identify the exploited vulnerabilities. This information is critical for effectively responding to and recovering from security incidents. Additionally, auditing and logging are often required for regulatory compliance, as many data protection and privacy regulations mandate the monitoring and recording of access to sensitive data. Regular audits of logs also help in ensuring that the API security measures are functioning as intended and assist in identifying areas for improvement. This is why auditing and logging are essential for proactive security monitoring, effective incident response, regulatory compliance, and continuous improvement of API security posture.
7. Restrict access to data
Sometimes, it’s okay to be paranoid! Restricting access to sensitive data is a key API security practice that involves implementing strict access controls to ensure that only authorized parties can access important information. This approach aligns with the principle of least privilege, effectively reducing the risk of data breaches and limiting the impact in case of security incidents. It's essential for compliance with data protection regulations like GDPR, HIPAA, and PCI DSS. By employing strategies such as role-based and attribute-based access control, and regularly auditing access rights, organizations can safeguard sensitive data, maintaining its confidentiality and integrity when accessed through APIs. This selective access is crucial for minimizing potential damages from compromised credentials or insider threats, and for ensuring that sensitive data is only accessible to those who genuinely need it for their specific roles.
8. Patch vulnerabilities
Patching vulnerabilities quickly is a vital API security best practice due to the rapid pace at which cyber threats evolve and exploit unaddressed weaknesses. Vulnerabilities in APIs can serve as entry points for attackers, leading to data breaches, system compromises, and other security incidents. Timely patching of these vulnerabilities significantly reduces the window of opportunity for attackers to exploit them. This practice is crucial not only for safeguarding sensitive data but also for maintaining the overall security and stability of the API ecosystem. Delay in patching can leave systems exposed to known threats, increasing the risk of targeted attacks. Additionally, regulatory frameworks often mandate timely updates as part of compliance requirements, making prompt patching essential for legal and regulatory adherence.
9. Use a Web Application Firewall (WAF)
A WAF serves as a protective barrier between an API and the internet, filtering and monitoring HTTP traffic to and from the API. This is crucial for defending against common web vulnerabilities and attacks, such as SQL injection, cross-site scripting (XSS), and other OWASP Top 10 threats. By analyzing and intercepting malicious traffic, a WAF can prevent harmful requests from reaching the API, thereby significantly reducing the risk of exploitation. Moreover, WAFs can be configured with custom rules tailored to the specific security needs of an API, offering a layer of defense that is both robust and adaptable. They also provide additional features like rate limiting, which helps mitigate denial-of-service (DoS) attacks, and can log traffic for further analysis, aiding in incident response and forensic investigations.
10. Use an API gateway
An API gateway acts as a central point of entry for API requests, providing a layer of abstraction between clients and backend services. An API gateway allows for the consolidation of authentication and authorization mechanisms, ensuring that only valid and authorized requests reach backend services. This centralization simplifies the implementation and management of security policies. Secondly, API gateways can enforce rate limiting and throttling, protecting against denial-of-service (DoS) attacks and ensuring the API's availability. They also offer capabilities for logging and monitoring traffic, which is vital for detecting and responding to potential security threats. Additionally, API gateways can handle SSL/TLS termination, providing secure communication channels. By offloading these security functions to the gateway, backend services are relieved of these tasks, allowing them to focus on business logic.
11. Monitor and act on every security anomaly
Monitoring and acting on every security anomaly is essential in API security for early threat detection and mitigation. Continuous monitoring enables real-time identification of unusual activities, helping to prevent minor issues from becoming major breaches. Prompt response to these anomalies is key to minimizing system impact and data compromise. This practice is also crucial for regulatory compliance and helps in refining security policies by providing insights into vulnerabilities.
12. Leverage API management tools
The OWASP list also refers to improper (API) inventory management. This may mean the ongoing availability of old (and less secure) versions of an API, even though users have been directed to use the newest version. Improper management may also result in the emergence of zombie APIs or shadow APIs.
API management tools help you keep track of every one of your organization’s APIs, throughout the entire life cycle of each API. By leveraging a central tool, you’ll have a single pane of glass through which you can monitor performance, deploy new versions, deprecate old versions, and track usage. Proper API management goes a long way toward ensuring their security.
REST API security testing
So you’ve built your API integrations and have a comprehensive plan to ensure that you’ve followed the top API security best practices. Congratulations! Now it’s time to conduct thorough REST API security testing to ensure that you haven’t overlooked any critical aspects of API security!
What is API security testing?
API security testing is a process that involves evaluating and verifying the security measures of an Application Programming Interface (API) to ensure it is protected against potential vulnerabilities, attacks, and unauthorized access.
What are the most important types of API security testing?
There are multiple types of API security testing. Here, we zoom in on the most important ones:
Dynamic application security testing (DAST)
DAST tools test APIs by sending real-world requests and observing the responses. DSAT is an advanced system for continuously evaluating and improving the security posture of an organization's digital infrastructure. By simulating a range of attack scenarios and probing for vulnerabilities, DSAT offers a proactive strategy in identifying and mitigating potential security risks. DAST tools are good at identifying vulnerabilities that can be exploited by attackers, but they can be time-consuming and resource-intensive.
Static application security testing (SAST)
SAST tools analyze the source code of APIs to identify potential security vulnerabilities. This type of testing is 'static' because it's done in a non-runtime environment. SAST tools scan an application’s code to detect flaws such as input validation errors, insecure dependencies, cross-site scripting (XSS), SQL injection, and other vulnerabilities that could be exploited by attackers. SAST tools are good at identifying vulnerabilities early in the development process, and thereby reducing the cost and effort required to address vulnerabilities later, but SAST tools can be difficult to set up and use.
Interactive application security testing (IAST)
IAST tools are deployed within a running application and monitor its behavior for signs of malicious activity. IAST tools are good at identifying vulnerabilities that are difficult to detect with other methods, but they can be expensive and intrusive.
IAST blends elements of both static (SAST) and dynamic (DAST) testing methodologies. This method allows IAST tools to detect issues in real-time, providing immediate feedback to developers. Unlike SAST, which analyzes static code, or DAST, which tests from the outside in a running application, IAST combines the best of both worlds: it assesses the application from within while it's running, capturing the context of data flow and user interactions. This approach enables IAST to identify a broader range of vulnerabilities, including those that are only evident during the application's execution, such as authentication issues, access control problems, and more complex business logic flaws.
Fuzzing
Fuzzing is a technique that involves sending large amounts of random data to an API to see if it can be crashed or otherwise compromised. Fuzzing is good at identifying vulnerabilities that are difficult to find with other methods, but it can be time-consuming and resource-intensive.
Fuzzing involves inputting large amounts of random data, or "fuzz," into a system in order to trigger unexpected or abnormal behavior, such as crashes, memory leaks, or unhandled exceptions. There are different types of fuzzing techniques, ranging from completely random data generation to more sophisticated approaches that use knowledge of the system's structure and expected inputs.
Take software to the next level after comprehensive API security testing
As the front door to your software applications, APIs are a common target of modern cyber attacks. Therefore, securing your APIs is not an option; it’s a necessity. By familiarizing yourself with common API security risks and vulnerabilities, you will be well-equipped to implement API security best practices. As your APIs become more secure, you can build software with higher confidence that it can stand up to the threats common in today’s digitally interconnected world.
If you’re building applications to facilitate in-app notifications, chat, voice/video calling, or live video streaming, you can leverage secure SDKs, APIs, and UI kits from Sendbird to get to market more quickly, in turn freeing up your developers to focus on building business value. Sendbird provides a secure messaging API and infrastructure, with all communication to and from Sendbird services encrypted using TLS/SSL.
Start a free trial or contact us to learn how you can build safe in-app communication with a secure communications API.