Search

Contact Us

Log in

Go back to blog

A Comprehensive Intro Guide to API Security

Tiago Mendo
Tiago Mendo

January 31, 2024 · 20 min read

When building an application, you need an interface to communicate with it, which can either be a user interface (UI), meant for users to interact with your application, or an application programming interface (API), meant for other systems to interact with your application.

Fundamentally, an API offers a service that provides methods and data formats that other systems can use to request actions and exchange information. When other systems send requests to an API for specific data or to perform actions, the API processes those requests (which may involve accessing databases, resources, or even other APIs) and sends back responses with data for the other systems to process.

In today’s world, APIs have become a fundamental piece of the digital landscape due to the vast number of providers and consumers of services through APIs that have grown hugely. Just think of the following real-world situations that illustrate this:

  • The sheer number of e-commerce platforms worldwide processing payments by integrating with API payment gateways like Stripe, PayPal, Square, and so on.
  • The immense variety of applications integrating with Facebook, Instagram, or X (ex-Twitter) through their APIs for users to share content and feeds.
  • Or the seamless connectivity between mobile apps, TV apps, car apps, home automation apps, etc., all through APIs.

Why is it So Important to Secure an API?

As the usage of APIs expands and the complexity of interconnected digital systems grows, so does the attack surface, which naturally leads to an increase in the risk of cyber attacks on APIs. The increasing need to create solid APIs with robust security to protect them and the whole digital ecosystem becomes evident.

If security is not adequately implemented, an API poses a significant risk due to the potential of attackers exploiting vulnerabilities with severe consequences. For example:

  • Compromise the integrity of your data.
  • Gain access to your data, resulting in data breaches.
  • Gain control of critical functionalities and compromise your service operation.

Of course, the consequences can go well beyond just an individual API since a breach of an API can have a domino effect both on the clients using it and on systems used by API, thus compromising the security of a whole ecosystem.

The Most Serious API Threats

OWASP API Security

In order to raise awareness of the most severe API security threats, the Open Worldwide Application Security Project (OWASP) investigates and releases a list of the most serious API security risks. You should check out the OWASP Top 10 API Security Risks to stay on top of the most severe threats and protect your APIs accordingly.

The security problems affecting APIs do not end here since this is not an exhaustive list. For instance, you should also check the OWASP Top 10 Web Application Security Risks, as they can also be relevant in the context of your APIs.

Nevertheless, here’s the list of OWASP’s Top 10 API Security Risks for 2023, for your convenience:

OWASP Top 10 API Security Risks for 2023

Risk Description
API1:2023 Broken Object Level AuthorizationAPIs tend to expose endpoints that handle object identifiers, creating a wide attack surface of Object Level Access Control issues. Authorization checks should be considered in every function that accesses a data source using an ID from the user.
API2:2023 Broken AuthenticationAuthentication mechanisms are often implemented incorrectly, allowing attackers to compromise authentication tokens or to exploit implementation flaws to assume other user’s identities temporarily or permanently. Compromising a system’s ability to identify the client/user, compromises API security overall.
API3:2023 Broken Object Property Level AuthorizationThis category combines API3:2019 Excessive Data Exposure and API6:2019 - Mass Assignment, focusing on the root cause: the lack of or improper authorization validation at the object property level. This leads to information exposure or manipulation by unauthorized parties.
API4:2023 Unrestricted Resource ConsumptionSatisfying API requests requires resources such as network bandwidth, CPU, memory, and storage. Other resources such as emails/SMS/phone calls or biometrics validation are made available by service providers via API integrations and paid for per request. Successful attacks can lead to Denial of Service or an increase in operational costs.
API5:2023 Broken Function Level AuthorizationComplex access control policies with different hierarchies, groups, and roles and an unclear separation between administrative and regular functions tend to lead to authorization flaws. By exploiting these issues, attackers can gain access to other users’ resources and/or administrative functions.
API6:2023 Unrestricted Access to Sensitive Business FlowsAPIs vulnerable to this risk expose a business flow - such as buying a ticket, or posting a comment - without compensating for how the functionality could harm the business if used excessively in an automated manner. This doesn’t necessarily come from implementation bugs.
API7:2023 Server Side Request ForgeryServer-Side Request Forgery (SSRF) flaws can occur when an API is fetching a remote resource without validating the user-supplied URI. This enables an attacker to coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall or a VPN.
API8:2023 Security MisconfigurationAPIs and the systems supporting them typically contain complex configurations meant to make the APIs more customizable. Software and DevOps engineers can miss these configurations or don’t follow security best practices regarding configuration, opening the door for different types of attacks.
API9:2023 Improper Inventory ManagementAPIs tend to expose more endpoints than traditional web applications, making proper and updated documentation highly important. A proper inventory of hosts and deployed API versions is also important to mitigate issues such as deprecated API versions and exposed debug endpoints.
API10:2023 Unsafe Consumption of APIsDevelopers tend to trust data received from third-party APIs more than user input and so tend to adopt weaker security standards. In order to compromise APIs, attackers go after integrated third-party services instead of trying to compromise the target API directly.

API Security Fundamentals

This section focuses on the most fundamental principles of API security that you should see as the cornerstone to establish a secure foundation for designing and implementing your APIs.

Authorization and Access Controls

Authorization and access controls determine what actions or resources users or systems can access:

  • Authorization - Authorization defines the policies and permissions granted to authenticated entities. A well-designed authorization system ensures that users or systems only have access to resources and functionalities you want them to.
  • Access controls - Access controls enforce the authorization policies, dictating how permissions are granted or denied based on predefined rules. This involves mechanisms such as:
    • Role-based access control (RBAC) - A user or system has an associated role, which defines the access permissions within the API.
    • Attribute-based access control (ABAC) - In this case, policies are enforced based on specific characteristics directly associated with the user, system, or even other characteristics. For example, the department, the location, or the time of day. This mechanism can also be called policy-based access control (PBAC) or claims-based access control (CBAC).

The tokens are a common method to implement authorization and are obtained during a setup process requiring authentication. They will carry information about the authorization policy and are validated by the API before granting access to the user or system.

The most common types of tokens are:

  • API Key - An alphanumeric token sent in requests to the API to identify the client. Typically, an API key gives full access to every operation an API can perform. It is commonly used in server-to-server communications or scenarios where simplicity is a priority.
  • Open Authorization (OAuth) - A token that is sent in requests to the API to make requests on behalf of the client without exposing its credentials. The token contains information that allows fine-grained control over the level of access granted. This is a more robust framework and excels in scenarios involving users. It is common to implement OAuth using two tokens:
    • An access token - The token that is sent in the requests. Optionally, an access token can expire.
    • A refresh token - The token that is sent requesting the new access token when the current one expires. 
  • JSON Web Tokens (JWT) - JWT is a compact and self-contained token sent in requests to the API to identify the client. The token contains a base64 encoded version of the data you need to determine the identity and scope of access. It has three parts: a header specifying the token type and signing algorithm, a payload with claims or assertions, and a signature for integrity verification.

A JWT provides a versatile means of transmitting information securely and is particularly useful in complex environments.

Implement one or a combination of these mechanisms depending on the security measures required for your APIs.

Data Encryption

Prevent attackers from reading data exchanged between a client and an API (data in transit) and stored data (data at rest) by encrypting your data.

  • Encryption in transit - This is implemented through protocols like HTTPS that automatically encrypt the data during transmission, making it unintelligible to anyone observing the network. For example, someone attempting to eavesdrop on the network in public Wi-Fis.
  • Encryption at rest - This involves protecting data stored in the disks or databases supporting the API. In the event of unauthorized access to the servers or data centers, the data will remain indecipherable to attackers.

Choosing robust encryption algorithms, keeping keys secure, and using proven cryptographic libraries are critical aspects of a comprehensive data protection strategy. Whether it is credit card details, user credentials, or sensitive business information, the application of encryption in transit and at rest ensures that your API handles critical data with confidentiality and resilience against potential attacks.

Input Validation

Securing APIs extends beyond authorization, access control, and encryption. Another important aspect to consider is the input validation to prevent injection attacks that exploit vulnerabilities by injecting malicious code into an application.

Inputs in requests to the API, like query parameters, for example, if not adequately validated, can become potential entry points for injection attacks. By validating the input data, you ensure it adheres to expected formats and standards as a barrier against injection vulnerabilities, such as SQL injection.

Define and implement strict input validation policies and ensure you choose highly secure and well-established libraries.

Best Practices for API Security

This section outlines a list of best practices for API security with some principles and actionable strategies that reinforce the resilience and reliability of your APIs against security threats.

The first three best practices confirm and enforce the importance of the security fundamentals already mentioned when we discussed the API Security Fundamentals. However, you must also look into the other best practices and consider applying them because they will improve your API security overall.

Authorization and Access Controls

Enforce granular control and restrict access to your API resources based on predefined roles or attributes. This ensures that users or systems only have the necessary permissions.
Adhere to the Principle of Least Privilege to ensure only the minimum level of access required to perform a specific task or function is granted to users or systems. This way, you can significantly reduce the risk of unauthorized access and data breaches.

Data Encryption

Employ encryption protocols like HTTPS to secure data in transit and implement encryption. Use TLS (Transport Layer Security) on all communications to your APIs and from your applications. TLS ensures confidentiality (can’t be read), integrity (can’t be changed), and authentication (it is from whom we expect) of your data during transmission.
As for data at rest, choose well-established encryption algorithms and tools to encrypt your disks and databases. Consider also the tokenization of particularly sensitive data, which replaces data with meaningless tokens to attackers, and only authorized parties can map those tokens back to the original data.

Input Validation

Scrutinize and filter data supplied in requests to prevent injection vulnerabilities. Implement thorough input validation to ensure data adheres to expected formats and standards.

Rate Limiting and Throttling

Implement mechanisms to control the frequency and volume of API requests. Rate limiting, also known as throttling, helps mitigate the risks of abuse and denial-of-service attacks. This can be implemented applicationally, involving a significant implementation time. Still, it might give you fine control for specific situations and even tie the rate limit to application concepts or logic.

Alternatively, you can use an API Gateway / Firewall, which is usually easier and provides a more complete solution to protect the whole API with minimal effort (see the last Best Practice).

Logging and Monitoring

Establish methodic logging practices and implement monitoring tools to detect and respond to unusual activities or potential security incidents. Regularly review logs and set up alerts for suspicious behavior. Ensure your logs can always answer the questions: Who?, When?, and What?.

Regular Security Audits and Testing

Conduct regular security audits, including penetration testing and code reviews during the development lifecycle, to identify and address potential vulnerabilities. Stay proactive in addressing emerging threats and evolving security standards.

API Versioning and Lifecycle Management

Implement versioning to allow for graceful transitions when introducing changes to your API. Establish clear lifecycle management practices to retire deprecated versions and maintain compatibility.

Secure Third-Party Integrations

Integrating with other APIs increases the dependency on third-party providers, as well as the complexity and challenges ensuring the security of your systems. In this sense, it is fundamental to fully assess the security risks concerning third-party APIs before integrating with them and plan the mitigations needed for the implementation phase.

Share Only Necessary Information

The principle of sharing only the necessary information dictates that an API should reveal the minimum amount of information while performing a specific transaction or interaction. This principle is essential for reducing the exposure of sensitive data and limiting potential attack vectors. This principle is also known as the Principle of Least Disclosure.

API Gateway

Last but not the least. Consider having an API Gateway as a central point for managing and securing your API ecosystem and reinforce some of the best practices described above.

An API Gateway provides multiple features:

  • Authorization - It can include support for API Keys, OAuth, JWT, and other protocols. It can also implement authorization policies to control access to specific API resources, ensuring that only authorized users or applications can access certain endpoints.
  • API Key Management - Handles the generation, distribution, and revocation of API keys or tokens, ensuring secure access to APIs and managing access credentials effectively.
  • Security Protocols and Encryption - Enforces security protocols such as HTTPS to ensure that data is encrypted and secure. Manages TLS termination, offloading the complexity of encryption from individual APIs.
  • Input Validation - Validates incoming requests to prevent common security threats like SQL injection, parameter tampering, and malicious uploads.
  • Request and Response Transformation - Modifies incoming requests and outgoing responses to adhere to security, compliance, or data format requirements.
  • Rate Limiting and Throttling - Protects the APIs against excessive traffic. 
  • Logging and Monitoring - Logs the API traffic, which can be valuable for debugging, auditing, and security analysis. Also provides real-time monitoring and analytics to track API performance, traffic patterns, and security issues.
  • API Versioning and Compatibility - Supports both older and newer versions, ensuring backward compatibility and a smooth transition between API versions.
  • Routing and Request Forwarding - Routes incoming requests to the appropriate backend services or microservices based on predefined rules and configurations.
  • Load Balancing - Optimizes resource utilization and enhances overall API reliability.
  • Caching - Improves API performance by reducing the load on backend servers and minimizing response times.
  • Scalability and High Availability - Scales horizontally to handle increased API traffic and can be deployed across multiple regions or data centers to ensure high availability and disaster recovery.
  • Cross-Origin Resource Sharing (CORS) - Enforces CORS policies to control which domains can access the API, helping prevent cross-origin request attacks and ensuring secure cross-origin API requests.
  • Policy Enforcement and Extensibility - Supports the enforcement of custom security policies and integrates with security plugins and extensions to adapt to evolving security threats and compliance requirements.

Testing the API Security

Security testing of APIs is fundamental to staying ahead of evolving threats. If done regularly and systematically, you definitely increase the robustness of your APIs against potential threats.

Types of API Security Tests

Within API security, various testing approaches can be employed to uncover vulnerabilities and ensure a more comprehensive identification of vulnerabilities in your APIs.

Here is a list of some test types to be considered:

  • Authorization Testing - Evaluate the effectiveness of the API’s authorization mechanisms (e.g., API keys, OAuth, JWTs) and check if authorization policies and controls are correctly implemented and enforced. Also, verify the secure generation, storage, and revocation of API tokens, keys, and credentials to prevent unauthorized access.
  • Data Security Testing - Assess the API’s handling of sensitive data. This includes verifying data encryption, proper data masking, and measures to prevent data leakage.
  • Penetration Testing - Conduct controlled attacks on the API to identify vulnerabilities and assess its resistance to real-world threats. Penetration testers simulate attacks like SQL injection, server-side request forgery (SSRF), and more.
  • Fuzz Testing - Detect potential security weaknesses by providing invalid or unexpected input to the API. Fuzzing aims to identify vulnerabilities related to input validation, data parsing, and error handling.
  • Error Handling and Logging Testing - Assess the API’s error-handling mechanisms and logging practices. Look for potential information leakage through error messages and evaluate the API’s ability to handle malicious or unexpected inputs.
  • Compliance Testing - Ensure that the API complies with industry-specific regulations and standards, such as GDPR, HIPAA, or PCI DSS, which dictate how to protect sensitive data.
  • Load Testing - Analyze the API’s behavior under heavy traffic conditions to determine its capacity and limitations to ensure the API can handle increased user loads without degrading performance or security. More importantly, it will also help prevent situations of Denial-of-Service (DoS) and Distributed Denial-of-Service (DDoS) attacks. 

Test Tools and Frameworks

Selecting the right tools and frameworks can significantly impact the effectiveness of API security testing. Here is a list of essential tools and frameworks:

  1. Probely DAAST (Dynamic API and Application Security Testing) - A robust and scalable tool for security tests to identify security vulnerabilities in web applications and APIs. Its extensive vulnerability and compliance tests, configuration and integration capabilities, automation, and detailed reporting make it a valuable asset for the security of your APIs.
    Learn more at https://probely.com/.
  2. OWASP ZAP (Zed Attack Proxy) - A versatile open-source security testing tool widely used for web application and API security assessments. It offers automated scanners for identifying common vulnerabilities for comprehensive testing.
    Learn more at https://www.zaproxy.org/.
  3. Burp Suite - A security testing tool used for penetration tests with specific features for API testing. It includes features for scanning and analyzing APIs, intercepting requests and responses, and identifying security vulnerabilities such as SSRF or SQL injection.
    Learn more at https://portswigger.net/burp.
  4. Postman - An API development and testing tool that simplifies the testing process. It allows testers to create and manage API requests, automate tests, and monitor responses. While primarily a development tool, it can be effectively employed for security testing due to its ease of use and automation capabilities.
    Learn more at https://www.postman.com/.
  5. Jenkins - An automation server commonly used for continuous integration and continuous delivery (CI/CD) pipelines. While not a testing tool per se, Jenkins can be leveraged to automate API security testing by integrating it with other security testing tools and scripts.
    Learn more at https://www.jenkins.io/.
  6. SwaggerHub Explore - A cloud-based tool for testing APIs documented with Swagger or OpenAPI specifications. It aids in sending requests and spotting potential security issues during development.
    Learn more at https://swagger.io/tools/swaggerhub-explore/.

Select the right tools and frameworks for your security testing goals, the nature of the APIs being tested, and the expertise of your testing team.

Securing the Gateways of the Digital World

API security should not be viewed as a luxury, but rather as a requirement. As APIs have become indispensable for modern applications and services in our increasingly interconnected digital landscape, they need safeguards shielding them against the numerous threats and malicious actors of the digital world.

Without proper API security in place, the gateways to sensitive data and functionality are completely unlocked, and anyone can just stride in, sometimes without anyone noticing until it’s too late.

We hope this guide gives you a good intro for you to know what you should be worried about, and also how to start minding the security of those gateways. Even when you think you’re protected, the art and cunning of those malicious actors at wild can’t be understated, and will keep on getting more technically sophisticated as time goes by.

Testing the security of your APIs is crucial, so you can regularly and systematically identify vulnerabilities so you can strengthen your APIs against threats. Who will you trust to do that for you?

API Security
Best Practices
Cybersecurity
Go back to blog