API Security: Authorization, Rate Limiting, and Twelve Ways to Protect APIs
41% of organizations suffered an API security incident, where a majority (63%) were data breaches.
This is despite 90% of them using authentication policies in place, according to a survey by 451 Research.
No surprises there, as authentication is just one piece of the API security puzzle.
In this blog, we’ll cover the 12 methods that technology leaders need to incorporate to secure and protect APIs.
1. Implement Strong Authentication Mechanisms
While authentication alone is not enough, it is one of the first methods engineering teams must incorporate to secure APIs.
While there are many best practices when it comes to implementing strong authentication mechanisms for APIs, here are the top 3:
1.1. Use Standard Protocols
Leverage standard authentication protocols such as OAuth 2.0, OpenID Connect, and token-based authentication using JSON Web Tokens (JWT).
Stay away from creating your own custom authentication schemes. These have been widely used and offer better interoperability and security.
1.2. Implement Token Expiry, Revoke, and Refresh
Since Tokens could be compromised, implementing token expiration, revoke and refresh mechanisms will limit damage in case of a compromise.
1.3. Validate Tokens on the Server Side
Validating tokens on the server side ensures that they have been tampered with or expired. Using cryptographic signing and validation mechanisms will also ensure the integrity of tokens.
2. Ensure Strong Authorization Practices
Authorization is all about implementing access control mechanisms so that even those requests with valid API keys only have access to the objects they have been assigned to.
Some best practices to follow while implementing authorization on APIs include:
2.1. Role-Based Access Control (RBAC)
In RBAC, users are assigned roles that define a set of permissions or actions that the user can perform. The user can access resources that are also defined based on their role.
For example, assume that an API provides access to financial data such as account balances, transaction history, and investment portfolios.
There are several different types of users who might need access to this data, each with different levels of permissions:
- Customer: A customer with an account with the financial institution can use the API to view their account balances and transaction history. They can also initiate transactions such as transfers to other accounts.
- Manager: A manager at the financial institution can use the API to view customer data for the customers they manage. They can view account balances and transaction history, initiate transactions on behalf of the customer, and modify the customer account settings.
- Compliance Officer: A compliance officer can use the API to view customer data for compliance purposes. They can view account balances and transaction history and flag suspicious activity for further investigation.
- Administrator: An administrator has full access to the API and can manage user accounts, roles, and permissions. They can also view all customer data and initiate transactions on behalf of any customer.
2.2. Attribute-Based Access Control
In ABAC, access decisions are based on a set of rules that specify the attributes required for a user to access a particular resource. These attributes can include information such as the user’s job title, department, location, security clearance level, and other relevant information.
For example, assume that a Healthcare API provides access to electronic health records (EHRs) for patients. The API is used by doctors, nurses, and other healthcare professionals to view and update patient records.
Here are some examples of attributes that could be used in an ABAC system for this API:
- Role: This attribute could be used to determine the user’s access level to patient records. For example, a doctor might have access to more sensitive patient data than a nurse.
- Diagnosis: This attribute could restrict access to patient records based on the patient’s medical condition. For example, a user might need special permission to view records for patients with certain diagnoses.
- Type of Data: This attribute could be used to restrict access to certain types of patient data, such as lab results or imaging studies. For example, a user might need special permission to view imaging studies.
- Location: This attribute could restrict access to patient records based on the user’s physical location. For example, a user might only be able to access patient records if they are within a certain building or geographic region.
3. Validate Inputs and Responses
Input validation is the process of checking user input to ensure that it conforms to the expected format, type, length, and range of values. Input validation can help to prevent attacks by identifying and rejecting malicious input before the API processes it.
This prevents SQL injection (SQLi), Cross-Site-Scripting (XSS), buffer overflows, and other attacks.
Here are the top three practices that help validate APIs to secure them against attacks:
3.1 Implement Positive Security Models
This method is highly effective because it enforces a strict set of allowed input values or patterns, ensuring that only valid data is processed. Focusing on what is allowed is simple, as APIs have strict boundaries. And these boundaries are usually defined in swagger files (OpenAPI Specifications). Essentially, this is a method to whitelist what is allowed and block everything that doesn’t conform to the expected pattern.
In AppTrana WAAP, DevSecOps teams have the capability to scan APIs for vulnerabilities and request positive security policies for every single API endpoint.
3.2. Validate Data Type, Format, Range, and Length
Validating these data attributes is essential for verifying that the input data matches the expected criteria. Ensuring the correct data type, format, range, and length of input parameters helps prevent common security issues like injection attacks and helps maintain the integrity of your application.
3.3. Use Validation Libraries and Frameworks
Most modern programming languages have validation libraries and frameworks that simplify the implementation of input validation. These libraries and frameworks usually cover various validation scenarios, including data type, format, range, and length validation, and often provide support for custom validation rules. Examples include Django validators for Python, Express-validator for Node.js, and so on.
These three methods, when combined, form a strong foundation for input validation in your APIs. However, depending on your specific use case and requirements, you may need to consider additional methods, such as JSON/XML Schema validation or custom validation rules, to ensure comprehensive input validation.
Here’s how input validation blocks vulnerability attacks right at the WAF.
4. Rate Limiting
Rate limiting plays a vital role in API management. It helps contribute to enhanced security, equitable resource allocation, improved performance and system availability, cost management, and the enforcement of quality of service.
Limit the number of requests an API client can make within a specified time frame to prevent brute force attacks, credential stuffing, and DDoS attacks and maintain service stability.
4.1. Choose the right rate-limiting strategy and set reasonable rate limits
Different rate limiting methods, like fixed-window, sliding-window, token bucket, or leaky bucket, can be used. Pick the best fit for your API’s needs, performance targets, and user experience.
Decide on suitable rate limits by looking at your API’s use, your resources, and the system’s capacity. Think about having different limits for various user types (such as free users, paid users, or subscription levels) or specific API features (for example, lower limits for actions that use a lot of resources).
While rate-limiting can be done on API gateways, bypassing that is relatively easy, and one should consider using a WAAP platform like AppTrana to detect anomalies in API traffic.
The other exclusive benefit of AppTrana is that the rate limits follow a behavioral model and track user behavior while setting rate limits. With API gateways, you might rely on static rate limits that need frequent updates.
4.2. Communicate rate limits to clients
Clearly communicate rate limits and policies to clients through API documentation and response headers (e.g., X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers). This helps clients understand the limitations and design their applications accordingly.
4.3. Provide clear error messages
When a client exceeds the rate limit, return a clear and informative error message, such as HTTP status code 429 (Too Many Requests), along with a description of the rate limit policy and when the client can resume making requests.
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 60
{
"error": {
"code": "rate_limit_exceeded",
"message": "You have exceeded the rate limit for this API. Please try again after 60 seconds."
}
}
In this example, the API is returning an HTTP 429 “Too Many Requests” status code, which indicates that the client has exceeded the rate limit for the API. The “Retry-After” header specifies the number of seconds the client should wait before making another request.
5. Encrypt Data Transmitted over APIs
Encryption is an essential security measure for protecting the confidentiality and integrity of data transmitted over APIs.
Here are some best practices for encryption to ensure API security:
5.1. Use Strong Encryption Algorithms
This is a critical best practice for encryption as the strength of the encryption algorithm determines how resistant the data is to brute-force attacks. Strong encryption algorithms such as AES (Advanced Encryption Standard) or RSA (Rivest-Shamir-Adleman) should encrypt data transmitted over APIs.
5.2. Use Transport Layer Security (TLS)
Using TLS (Transport Layer Security) is a crucial step in encrypting data in transit between the client and the server. TLS provides secure communication between client and server over the internet and is a widely used protocol that has been extensively tested for security.
5.3. Disable Weak Cipher Suites
Disabling weak cipher suites and protocols such as SSL (Secure Sockets Layer) and TLS 1.0/1.1 is important to protect against known vulnerabilities. These protocols have been deprecated due to their known vulnerabilities and are no longer considered secure. By disabling these weak cipher suites, organizations can help to ensure that known security weaknesses do not compromise their API’s encryption.
6. Monitoring and Logging
Monitoring and logging are important components of a comprehensive API security strategy. By implementing effective monitoring and logging practices, organizations can improve their ability to detect and respond to security incidents, comply with industry standards and regulations, and continuously improve their security posture.
This log indicates that User1 attempted to access an admin endpoint restricted to authorized personnel only. The fact that the request was rejected with a 403 Forbidden status code suggests that the access attempt was unauthorized.
This log entry could be indicative of a security incident, such as a user attempting to escalate privileges or gain unauthorized access to sensitive information. It could also indicate that an attacker is attempting to exploit a vulnerability in the API to gain access to privileged information or functionality.
7. Perform Regular API Security Testing
Conduct regular security tests, including penetration testing, vulnerability scanning, and code reviews, to identify and fix potential security issues.
Here is a detailed checklist of all use cases you could test for while performing penetration testing on APIs.
With the Indusface Infinite API scanner, you get access to unlimited scans, where a manual pen test and a revalidation test are included in one license.
8. Implement Security Headers
Security headers are an important component of API security and can help protect against various attacks, such as cross-site scripting (XSS), clickjacking, and MIME sniffing.
Best practices for implementing security headers include:
8.1. Content Security Policy (CSP)
CSP is a security header that prevents cross-site scripting (XSS) attacks by allowing the server to specify which content sources are trusted. By defining a whitelist of trusted sources, CSP can prevent malicious scripts from being executed on the client’s browser.
8.2. Cross-Origin Resource Sharing (CORS)
CORS is a security header allowing resources from one domain to be accessed by another. By implementing CORS, APIs can ensure that only authorized domains are allowed to access API resources, preventing unauthorized access by malicious domains.
8.3. HTTP Strict Transport Security (HSTS)
HSTS is a security header instructs browsers to only connect to the server using HTTPS. By enabling HSTS, APIs ensure that all communication with the server is encrypted and prevent attackers from intercepting sensitive data.
8.4. X-XSS-Protection
X-XSS-Protection is a security header that enables the browser’s built-in XSS protection mechanism. By enabling X-XSS-Protection, APIs can prevent cross-site scripting (XSS) attacks by instructing the browser to block potentially malicious scripts.
8.5. X-Frame-Options
X-Frame-Options is a security header that prevents clickjacking attacks by instructing the browser not to render the API in a frame or iframe. By implementing X-Frame-Options, APIs prevent attackers from tricking users into clicking on malicious links or performing actions on the API without their knowledge.
By following these best practices for implementing security headers, organizations can help improve the security of their APIs and prevent various common attacks.
9. Implement Error Handling Best Practices
Sometimes, error messages could expose any system or API details that attackers could exploit. Implementing error-handling best practices, therefore, becomes critical.
ERROR: Syntax error in SQL statement "SELECT * FROM users WHERE username='admin';[*]'; nested exception is java.sql.SQLException: ORA-00933: SQL command not properly ended
In this example, the error message is generated when a SQL query to retrieve user data encounters a syntax error. The error message includes the SQL query string and indicates that the query was not properly ended. The error message is generated by the API’s backend system and is returned to the client as part of the error response.
An attacker could potentially use this error message to perform a SQL injection attack. The attacker could modify or retrieve data from the API’s backend database by manipulating the SQL query string and injecting malicious code. The attacker could also use the error message to gain insight into the API’s backend infrastructure and identify vulnerabilities or weaknesses that could be exploited.
Here is a better way to display the error:
ERROR: An unexpected error occurred while processing your request. Please try again later or contact support for assistance.
In addition to this generic error message, it is best practice to log the specific error details for debugging and troubleshooting purposes. However, this information should only be accessible to authorized personnel and not be exposed to clients or end-users.
Organizations can protect sensitive data and prevent attackers from exploiting API vulnerabilities by implementing proper error-handling practices.
10. Follow Secure Coding Practices
According to a study by IBM, fixing a security flaw while developing could be 20X cheaper than fixing it later.
This could be eliminated altogether by following secure coding practices. While there are many sources to learn this, we would recommend OWASP, SANS 25, NIST, Microsoft Security, and AWS Well-Architected Framework as references.
11. Use an API Gateway
While all the above are best practices for securing APIs, API gateways are tools that can help dev teams in implementing most of the above best practices.
API gateways are used to manage and secure API endpoints. They provide a centralized location to enforce security policies, manage authentication and authorization, and implement additional features like rate limiting, logging, and load balancing.
12. Deploy a WAAP Solution
While API gateways provide some security, it is prudent to deploy a WAAP solution because of the following reasons:
12.1. API Discovery
Dev teams often lose track of the inventory of APIs, which leads to exploits of old versions of APIs. A modern WAAP platform like AppTrana provides access to a API discovery feature that helps in finding shadow, rogue, and zombie APIs. Once discovered, dev teams could then protect these APIs from exploits.
12.2. API Vulnerability Scanning
One of the first steps to protect APIs is to understand if they are vulnerable. The OWASP API top 10 is the most popular standard to test for API vulnerabilities.
On the AppTrana WAAP, you have a bundle that includes unlimited API scanning and a penetration test on API endpoints. Once you fix the vulnerabilities, you can also request a revalidation test.
12.3. Comprehensive Security Coverage
WAAP solutions often have advanced capabilities for detecting and mitigating threats, leveraging machine learning and behavioral analytics to identify and block malicious activity using both positive and negative security policies.
WAAP platforms also bundle WAF, DDoS, Bot protection, and threat intelligence that go above and beyond what an API gateway can provide in terms of API security.
While this is a comprehensive list of everything you can do to secure your APIs, most organizations use a combination of the above depending on their unique needs.
That said, an API gateway + a WAAP platform like AppTrana would cover most bases regarding securing APIs.
Stay tuned for more relevant and interesting security updates. Follow Indusface on Facebook, Twitter, and LinkedIn