Guide To API Security Best Practices
In the last few years, APIs have played a significant role in how applications work. Modern web applications rely heavily on them to transfer data and perform actions between components of the same application and its database.
As we’ve seen in cases like the Twitter breach where data from over 5.4 million users was compromised and Peloton’s API hack, where the private data such as location and avatar photos of over 3 million users (including President Biden) was exposed, API security is an essential component of overall security posture. These hacks resulted in user data breaches, financial loss for the affected company, and customer dissatisfaction.
To help you protect your customer’s sensitive data and improve your overall security posture, effective API security is critical. This article will review eight essential API security best practices that can help organizations get API security right.
Summary of key API security best practices concepts
The table below summarizes the API security best practices this article will explore
{{banner-small-1="/design-banners"}}
Eight API security best practices
APIs are the cornerstone of digital businesses. That also makes them an attractive attack surface for modern threat actors. The eight API security best practices below can help companies limit the risk of a breach and improve their overall security posture.
API security best practice #1: Use strong authentication and authorization mechanisms
According to OWASP Top 10 API Security Risks, broken authentication is the second biggest risk for APIs in 2023. First, let’s make the difference between authentication and authorization clear:
- Authentication provides your identity (e.g., with credentials) to the API backend.
- Authorization is the permissions you are granted by the system based on your identity.
APIs should only be available to users who have first provided evidence of their identity. Then, based on their identity, allow them to perform authorized actions. It is equally crucial to restrict unauthenticated users from performing actions on the API as it is to restrict unauthorized users who are authenticated but attempting to perform higher-level (e.g., administrative) actions.
The most popular API authorization mechanisms in modern applications are JWT and OAuth 2.0. They provide two different approaches to authorization, stateless and stateful.
JWT stands for JSON Web Token. It is a token format containing information regarding the user (username, account details, etc.) which is encoded in URL via base64 encoding and contains:
- The header in cleartext, consisting of the algorithm used and the token type,
- The payload in cleartext, and
- The payload’s digital signature
The payload is digitally signed with the cryptographic private key of the server, usually using one of the three following algorithms:
- Hash-Based Message Authentication Codes algorithm (HMAC)
- Rivest-Shamir-Adleman algorithm (RSA)
- Elliptic Curve Digital Signature Algorithm (ECDSA)
The server receives the cleartext data, hashes it, and compares the result with the digital signature. That way, no token that is not signed with the private key can be forged, ensuring authentication and authorization.
OAuth 2.0 is a protocol that verifies what resources a third party may access on behalf of the user that authorized it. It involves the application the user wants to access through the API and the API itself, which the user utilizes to get an authorization (or access) token.
Ensuring authentication and authorization is the first and most important API security best practice. Improper authentication and authorization can have severe negative impacts. For example, earlier in 2023, the data of millions of Bangladeshi citizens was accessible through an insecure API that had neither authentication nor authorization mechanisms.
Web scanners like Burp Suite can detect authentication and authorization issues. API-focused products can specifically analyze API specifications for vulnerabilities such as weak authentication, basic authentication, and no authentication.
API security best practice #2: Encrypt API traffic with SSL/TLS
The HTTPS protocol is a must for building secure applications and APIs. APIs can transfer sensitive information between the server and the end user. Encrypting that data is crucial for preventing eavesdropping attacks such as a man-in-the-middle attack.
A man-in-the-middle attack is when an attacker places themselves inside a network between the communication of a victim user and a server on this network or the Internet.
Without HTTPS, communication between the end user and the server is sent in cleartext, allowing the attacker to read sensitive information. The intercepted information may not be the only sensitive data the API transmits. Cookies and tokens compromised from an API call can allow an attacker to hijack a victim’s session.
With HTTPS, data in transit is encrypted using SSL/TLS. This makes it effectively impossible for someone to turn them into cleartext without the private key, ensuring the confidentiality of the communication.
{{banner-small-2="/design-banners"}}
API security best practice #3: Apply rate limits
Protecting your API from Denial of Service (DoS) attacks is as important as any other weakness. Rate-limiting protection helps prevent DoS attacks from compromising a system. Web application firewalls (WAFs) such as AWS WAF typically include some limited rate-limiting capabilities.
Rate limiting also reduces the risk of brute-force attacks. One-time password (OTP) submissions, password submissions, and username lookups are a few of the sensitive actions that need to be protected from brute-forcing.
For rate-limiting functions based on the service they provide, there’s a need for behavioral analysis. Suppose there is a checkout and a payment API endpoint. If a user is abusing the payment endpoint without having checked out, their requests should be limited.
As mentioned, WAFs include rate-limiting solutions that can help your security posture. But the use of rate-limiting alone based on static indicators, such as IP address, session ID, and cookies, has flaws and can be bypassed by experienced attackers. A dynamic, behavior-based rate-limiting approach can save time and improve threat detection accuracy. Tooling that implements reinforcement learning for API security can be particularly useful for behavioral analysis.
API security best practice #4: Handle error messages securely
Behind every API, there are technologies that handle data either from user input or retrieved from a database. Exceptions and errors to occur during processing are common. Applications must address these errors and prevent the API from exposing backend information about the technologies behind it.
Error messages that reveal information about backend systems and technology stacks give an attacker information they can use to exploit the API and the systems behind it. Hiding this information by printing vague error messages back to the user provides the API with an extra layer of protection. E.g., instead of printing the whole SQL stack trace error, which can reveal what technology the backend is using, one can return a simple message such as “There was an error with your request.”
API security best practice #5: Sanitize user input
Technologies behind an API must process user input so an API can serve the data a user requested. Unfortunately, not all user input is benign.
Malicious user input, like mass assignment attacks, can result in server-side and client-side issues, depending on the API’s behavior. Server-side issues such as SQL injections and web cache poisoning can occur from insecure user input handling. Similarly, client-side vulnerabilities may also arise from user input based on the API's structure and use. Common issues, such as cross-site scripting (XSS), to more unique ones, such as cross-API scripting (XAS), where the API presents the malicious user input in a sink, such as the website's front end.
The malicious payloads can vary from cross-site scripting, SQL injection, and local file inclusion/read payloads to logical bug payloads. Typical malicious payloads include:
XSS (first 2) and SQLi (the remaining 3) payload examples
Encoding user input, escaping special characters, and putting the API behind a WAF like Cloudflare, Akamai, or Sucuri that can detect malicious user input can mitigate vulnerabilities based on “bad” input.
API security best practice #6: Require versioning and documentation
Like any other software, APIs are constantly being developed. That means deprecating or updating endpoints or even creating new features. Versioning allows gradual updates while maintaining compatibility with the already-existing functions of the API. It also helps to patch faster and allows better testing, as it is recommended that a new branch/version should be created solely for testing purposes.
All the new changes and older API functions should be properly documented so that users and developers can stay up-to-date with the latest changes. Also, it allows the people that develop, maintain, and run the API to understand it better.
Automation should be used to detect these problems, saving valuable manual effort and time for the developer. Some tools can generate documentation automatically and detect “zombie APIs” (deprecated endpoints). Specifically, the highlighted tool can do this based on OpenAPI specification files and by analyzing traffic. If a deprecated endpoint appears in the traffic, teams should have a way to remediate the issue.
For a deeper dive into the benefits of versioning and API documentation, check out Why Complete API Documentation Makes Your APIs More Secure.
API security best practice #7: Avoid excessive data exposure
Excessive data exposure is the issue of revealing too much information to API users. For example, exposing admin information to regular users that are not admins or disclosing information and sensitive data to any unauthorized user.
Usually, user roles follow a hierarchy. The hierarchy starts with admins that are supposed to see everything. The lower we go in this hierarchy, the less information is available. This is important to avoid any unnecessary information disclosure, such as the username of an admin that modified an object.
Also, hiding any information irrelevant to the user, regardless of the user's role is equally important. APIs often return all possible information on an object, and then the web application front-end filters out the data it doesn’t need. API security best practices dictate such data exposures should be avoided because they can be abused, especially when combined with other vulnerabilities. Instead of having API endpoints that return a massive amount of data that the front-end filters, creating many endpoints with specific scope as to what data they return is advised. For example, the API call /getinfo, which may return all the information about an account, can be broken down to /getusername, /getcontactdetails, etc. That way, the application's front-end can pick what data it needs and from which endpoints, avoiding unnecessary data exposure.
API security best practice #8: Use HTTP verbs correctly
All API operations can be summarized into a simple acronym: CRUD (Create, Read, Update, Delete). A user can make these four basic requests while using an API. These actions are associated with an HTTP verb that can carry an operation. While many HTTP verbs can do more than one thing, it is highly advisable to use the following pattern:
It is important to keep a pattern for a better understanding of the API by the developers. When the developers have a clear understanding of the API they are building, they also have a clear vision of how its security design should be. Also, consistent use of HTTP verbs can add an extra layer of security.
For example, let's look at this HackerOne report. The GraphQL endpoint usually utilizes a cross-site request forgery (CSRF) protection through an HTTP header on POST endpoints that are used to edit or create a resource. By allowing GET requests to edit or create resources, this protection gets omitted, leaving the API users exposed to CSRF attacks which, when leveraged by an attacker, can make a victim perform unwanted actions.
Having a straightforward API design with rules that developers have to follow avoids miscommunication which can lead to security misconfigurations.
{{banner-large-white="/design-banners"}}
Conclusion
APIs have increasingly gained more and more popularity over the last few years. That also means that APIs are becoming the target of attackers for financial gain. The baseline of defense for securing your API and your digital assets is to enforce API security best practices. It is also highly advisable to establish a continuous monitoring system and remain up-to-date with new practices as the field of cybersecurity evolves.
Contact Impart Security at try.imp.art for more API security tips and best practices and be sure to follow us on LinkedIn for the latest product news and updates.
Subscribe to our LinkedIn Newsletter to receive more educational content
Guide To API Security Best Practices
Learn how to protect customer data and improve security posture with 8 essential API security best practices.
API Pentesting Methodology
Learn how to scope an API, address the top five attacks, and report and retest vulnerabilities during API penetration testing.
API Attacks
Learn how API attacks, such as Broken Object Level Authorization, can lead to unauthorized access to confidential data and how to protect against them.
API Security Monitoring
Understand the best practices for monitoring your API, as well as some key features to look for when evaluating an API monitoring solution.
API Security Testing
Learn how to evaluate the security of an API and prevent common threats and vulnerabilities with twelve essential API security testing best practices.
API Security Tools
Learn how to use API security tools for offensive and defensive strategies, such as OWASP ZAP, Burp Suite, ffuf, Kiterunner, Postman, Swagger, and Im
API Security Solutions
Learn how to select a robust API security solution with features, best practices, and guidelines to ensure secure data exchange.
Secure API Development
Explore a detailed guide to API development with security at its core, covering the entire SDLC. Gain insights into best practices and practical tips for comprehensive API protection.
API Gateway Security
Learn how to secure your API gateway with 8 best practices, from authenticating users to rate limiting and hardening your apps.
OWASP Top 10 API
Learn how to prevent API security breaches with OWASP API Security Top 10 and implementing best practices for attack prevention.
API Authentication Security Best Practices
Learn how to implement robust API authentication security measures with best practices and example solutions.
API Discovery
Learn how to discover, document, and manage APIs for organization owners and developers with this article on API discovery best practices.