Mobile devices have become a ubiquitous part of our daily lives, and they are increasingly used for business and personal transactions. Mobile apps often rely on APIs to communicate with back-end systems and other third-party APIs, making them an essential component of modern mobile apps. However, APIs also create security risks that need to be addressed to prevent data breaches, cyber attacks, and other security incidents.
Developers must adopt best security practices to ensure the security of mobile APIs and implement robust security measures that go beyond addressing the OWASP API Top 10 security threats. One such measure is locking down the API server with genuine instances of the mobile app via Remote Mobile App Attestation, which goes above and beyond standard and advanced best security practices.
In the following sections, we will discuss some of these best security practices in more detail and provide guidance on how to use them effectively to secure mobile APIs and protect user data. This blog post also outlines where the developer should consider the use of Approov to enhance the security of their mobile APIs. To learn about best security practices for mobile apps you can read our previous article Mobile App Security Best Practices.
Secure code practices are an essential aspect of API security. Even if all other security measures are in place, if the underlying code is vulnerable, the API will still be at risk of compromise. Here are some secure code practices that developers should follow to ensure the security of their APIs:
Developers should follow secure coding standards such as those recommended by organizations like OWASP to minimize the risk of common coding vulnerabilities such as buffer overflows, SQL injection, and others.
Input validation is crucial to prevent malicious input from causing unintended actions. APIs should validate all user input, including data sent via HTTP headers, query strings, and request bodies to prevent injection attacks. For more details see section below on Input Validation.
Proper error handling is an essential aspect of secure coding. Developers should ensure that all errors are handled appropriately, and no sensitive data is leaked to the end-user in case of errors.
APIs should be designed with the principle of least privilege in mind, meaning that each API endpoint should only grant access to the data and functionality required for the specific task by using role based access controls (RBAC). RBAC involves assigning users to roles that define their access privileges and limiting access to resources based on those roles.
To prevent unnecessary data exposure, it is recommended to avoid returning large API responses with data that is not needed for the client's task. For REST APIs, developers can consider implementing a mechanism where the client can specify which fields are required in the response using an URL parameter. It's also essential to ensure that only fields allowed in the role-based access control (RBAC) are provided. As for GraphQL APIs, it's crucial to set limits for how deep the graph can go and how many entities can be queried in a single request. Failure to do so may lead to server overloading, as well as enable attackers to extract an excessive amount of data in a single request.
Secure data storage is an essential aspect of secure coding. Developers should ensure that all sensitive data is stored securely using the latest encryption and hashing algorithms.
Using safe coding libraries that are regularly updated and maintained is an essential aspect of secure coding. Developers should ensure that they are using the latest version of the library and avoid using deprecated libraries.
Developers should not use hard-coded secrets. Instead retrieve your secrets from the environment or better from a secrets vault.
Use the services of security researchers to perform regular code reviews to identify potential security vulnerabilities in the code base. This can help to identify issues such as insecure coding practices, code injection vulnerabilities, and SQL injection vulnerabilities.
Developers should perform regular vulnerability scans on each release, to detect potential security weaknesses in their code and third-party libraries and address them proactively, ideally before releasing.
Developers should implement security testing throughout the software development lifecycle, including static code analysis, dynamic testing, and manual code review. This can help identify potential security issues and allow for their timely resolution.
By following these secure code practices, developers can help to ensure the security and integrity of their APIs, reducing the risk of data breaches and cyber attacks. This can be enhanced by implementing Approov's remote mobile app attestation, which will even protect a vulnerable API from attacks. This is because only genuine instances of the mobile app that pass the attestation process will receive valid Approov tokens to add to the header of each API request. As a result, any unauthorized attempts to access the API will be rejected when such a token is invalid, expired or not present in the header of the API request, thus enhancing the security of the API, which allows for the API developer to fix any vulnerabilities in the API without worrying about it being actively exploited by attackers.
Secure data storage is an essential component of API security best practices, as it helps protect sensitive data from unauthorized access or theft. Here are some key considerations for secure data storage in the context of API security:
All sensitive data, including user credentials and personal information, should be encrypted while at rest and in transit. Encryption helps ensure that even if an attacker gains access to the data, they cannot read or use it. This includes data such as user credentials, personally identifiable information, and other sensitive data.
Sensitive data should be stored separately from non-sensitive data to minimize the attack surface of the API server.
Access to sensitive data should be restricted to authorized users and systems. This can be achieved through user authentication and authorization mechanisms, such as multi-factor authentication and role-based access control.
Developers should use secure storage mechanisms that are designed to protect against data breaches and theft. This includes using encrypted databases, secure file storage, and secure cloud storage solutions.
Developers should have clear data retention policies in place that dictate how long sensitive data should be stored and when it should be securely destroyed. This helps ensure that data is not kept longer than necessary and reduces the risk of data breaches.
Regular backups of the API data should be taken and stored securely encrypted in a separate location. This can help prevent data loss in the event of a security incident or system failure. Test regularly that you can recover from your backups or you may be up to a bad surprise when the time arrives to use one in an emergency.
Developers should regularly assess the security of their data storage mechanisms to identify and address any vulnerabilities or weaknesses. This can be done through regular security audits and penetration testing.
By implementing these best practices, mobile app developers can ensure that sensitive data is protected from unauthorized access or theft, reducing the risk of data breaches and other security incidents.
Secure communication is critical to ensuring the confidentiality and integrity of data transmitted between mobile apps and API servers. Without proper security measures in place, attackers can intercept and eavesdrop on sensitive data, compromising the security of the mobile app and API and exposing user data to theft or misuse.
To secure communication between mobile apps and API servers, developers should implement the following best practices:
Developers should use the latest and most secure versions of the TLS protocol to ensure secure communication between the mobile app and API server, and disable outdated protocols, such as SSL, to ensure the highest level of security. TLS 1.3 is currently the most secure version and should be used where possible.
Ensure that sensitive data transmitted between the API server mobile app is encrypted in both ways, preventing intercepted data from eavesdropping by attackers. You can use Approov App Instance Secure Strings to decrypt the sensitive data received from the API and to encrypt the sensitive data sent from the mobile to the API backend. With App Instance Secure Strings, the decryption key is only provided by the Approov cloud service to mobile apps that pass the Approov remote mobile app attestation. This ensures that the decryption key is only given to genuine and valid instances of the mobile app, and not to attackers or malicious apps.
While the implementation of pinning belongs to the mobile app developer, the API developer could make this as a requirement to use the API, because this will reduce the attack surface on the API, once it will not be trivial to extract the API key via a MitM attack.
Certificate pinning is a highly effective technique that can significantly enhance network security. By implementing certificate pinning, mobile app developers can specify a set of trusted certificates that the mobile app should accept, the ones used by the API(s), instead of relying solely on the operating system's list of trusted certificate authorities (CAs). This makes it more difficult for attackers to impersonate the server and intercept data transmitted between the app and server.
In addition to specifying a set of trusted certificates, developers can also use public key pinning to further enhance security. This involves verifying that the server's public key matches the pinned public key before establishing a connection. By doing so, the app can ensure that it is connecting to the intended API server and prevent man-in-the-middle attacks.
While implementing certificate public key pinning is a valuable security measure, mobile app developers should also be aware that it is possible to bypass certificate pinning. Therefore, it is recommended to use dynamic certificate pinning as a solution to this issue. This approach involves dynamically updating the pins for the certificate public key, making it harder for attackers to bypass certificate pinning. By taking these measures, mobile app developers can significantly enhance the security of their applications and protect sensitive data transmitted between the mobile app and API server, while simultaneously decreasing the API's attack surface.
Input validation is a critical aspect of mobile API security that ensures that data submitted by users is safe and does not contain malicious code or scripts that can compromise the security of the API server. Input validation is necessary because attackers can inject malicious data into the mobile app, which can then be transmitted to the API server and executed, resulting in data theft, application malfunction, or system compromise.
To ensure proper input validation, API developers should implement the following best practices:
Developers should validate all input data received from the mobile app and reject any data that does not conform to the expected format or type. For example, if a mobile app expects a phone number, the API server should reject any input that does not contain a valid phone number.
Server-side validation is essential for ensuring that input data is not only validated on the client-side but also on the server-side. Developers should implement server-side validation checks to ensure that input data is properly validated before it is processed by the API server.
Input sanitization involves removing any potentially malicious code or scripts from input data to prevent injection attacks. Developers should use input sanitization techniques such as encoding, filtering, and escaping to remove any potentially malicious code or scripts from input data.
By implementing these best practices, developers can ensure that input data submitted by users is safe and does not contain malicious code or scripts that can compromise the security of the mobile app or API server.
Authentication and authorization are critical components of mobile API security that ensure that only authenticated and authorized users have access to sensitive data and resources. Without proper authentication and authorization mechanisms in place, attackers can gain unauthorized access to user data, resulting in data theft, misuse, or compromise.
To ensure proper authentication and authorization, developers should implement the following best practices:
Token-based authentication is a widely used mechanism for securing APIs. It involves issuing tokens to authenticated users and validating those tokens for subsequent requests, providing an additional layer of security. Developers should use token-based authentication mechanisms, such as OAuth2 or JSON Web Tokens (JWT). OAuth2 is an authorization framework that enables users to grant access to third-party applications without sharing their credentials.
Developers should prefer to use OAuth2 or similar authorization frameworks for user authentication to not have to deal with the burden of keeping the user credentials secure and not have them leaked in a data breach.
The API server must ensure that it only accepts tokens signed/encrypted with secure algorithms that expire after a very short period to prevent unauthorized access. Protecting authentication tokens from theft by storing them securely on the mobile device and expiring them after a certain period. You can also use Approov App Instance Secure Strings to store the tokens securely encrypted in the mobile app.
Developers should implement strong 2FA mechanisms and avoid weak ones, such as text messages (sms), to ensure that only authorized users can access the API server via the mobile app. Authentication mechanisms without 2FA, such as passwords alone, can be easily compromised via credential stuffing attacks, leading to unauthorized access to sensitive data directly from the API server or via the mobile app.
Authorization checks ensure that only authenticated and authorized users have access to sensitive data and resources. Developers should implement proper authorization checks at the API server level to ensure that users only have access to resources they are authorized to access.
Limiting access to sensitive data is critical in mobile app security. Developers should ensure that users only have access to the data and functionalities that they need to perform their tasks.
Role-based access control (RBAC) is a widely used mechanism for implementing authorization checks. Developers should use RBAC to enforce proper access control and limit the risk of unauthorized access to sensitive data.
Also, when performing high sensitive operations partial or complete authentication should be required again, password and/or 2FA, even if the current session is still valid.
In case you need to support password-based authentication, it is crucial to prioritize the implementation of strong passwords as a fundamental aspect of your API security. To achieve this, developers should enforce strict password policies that require users to create complex passwords that are difficult to guess and have not been breached before, which can be verified using a service like haveibeenpwned.com.
Furthermore, when storing passwords, it is recommended to hash and salt them to ensure they cannot be easily compromised. It is important not to attempt to create a custom solution for this, as it can be prone to security vulnerabilities. Instead, use a mature and well-tested library that stays up to date with the latest security practices for secure password storage.
Enforcing password policies is essential to ensure the protection of user accounts on your API. These policies should require users to change their passwords in case they have been compromised in a data breach, which can be verified using a service like haveibeenpwned.com. Additionally, password policies should prohibit the reuse of old passwords to avoid the risk of attackers using previously compromised passwords.
Moreover, it is advisable to implement password policies that lock out users after a certain number of failed login attempts to prevent brute force attacks and credential stuffing attacks against the API authentication endpoints. This adds an extra layer of security and mitigates the risk of unauthorized direct access to user accounts on the API. By enforcing these password policies at the API level, mobile app developers can significantly improve the overall security of their applications and provide users with a secure environment to manage their accounts.
To ensure that your API backend remains secure and does not leak sensitive data, it is imperative to restrict access to only genuine instances of your mobile apps. To achieve this, it is recommended that you implement a solution that can provide end-to-end security for both your mobile app and API servers. By doing so, attackers are prevented from accessing and fulfilling API requests.
One effective way to achieve this is by using the Approov remote mobile app attestation solution that provides dynamic certificate pinning out of the box. This approach allows the API server to confirm the authenticity of the API request and serve it without the risk of exposing sensitive data to attackers. For more information on how to implement this approach, refer to the article How to Protect Against Certificate Pinning Bypassing.
By implementing these best practices, developers can ensure that only authenticated and authorized users have access to sensitive data and resources, reducing the risk of data theft, misuse, or compromise.
Error handling and logging are critical components of mobile API security that ensure that errors and exceptions are handled properly, and detailed logs are generated to assist in troubleshooting and security analysis. Proper error handling and logging help to identify and address security vulnerabilities and reduce the risk of data theft or system compromise.
To ensure proper error handling and logging, developers should implement the following best practices:
Custom error messages provide more detailed information about errors and exceptions, helping developers diagnose and fix security issues more efficiently. Developers should use custom error messages that do not reveal sensitive information, such as passwords, usernames, or internal server information that will expose the system to additional risks.
Exception handling ensures that errors and exceptions are handled properly, reducing the risk of system compromise or data theft. Developers should implement proper exception handling at the API server level to ensure that errors and exceptions are caught, logged, and appropriately handled.
Logging is a critical component of mobile API security that enables developers to analyze system behavior and identify security issues. Developers should use secure logging techniques that ensure that sensitive information, such as passwords or credit card information, is not logged. They should also ensure that log files are properly secured and encrypted to prevent unauthorized access.
Detailed logs provide valuable information for troubleshooting and security analysis. Developers should generate detailed logs that record all user and system activity, including requests, responses, errors, and exceptions, and store them encrypted in a secure and centralized location.
By implementing these best practices, developers can ensure that errors and exceptions are handled properly and logged securely, reducing the risk of data loss or compromise and enabling more efficient diagnosis and fixing of security issues.
Denial of Service (DoS) attacks are a significant threat to mobile APIs as they can disrupt the availability of the API server and cause a loss of service to users. DoS attacks involve overwhelming the API server with excessive traffic or requests, rendering it unavailable to legitimate users. To protect against DoS attacks, developers should implement the following best practices:
Rate limiting involves limiting the number of requests that can be made to the API server within a specific time frame. Developers should implement rate limiting to prevent excessive traffic from overwhelming the API server and ensure that it remains available to legitimate users.
Content Delivery Networks (CDNs) are distributed networks of servers that help to distribute traffic and reduce the load on the API server. Developers should use CDNs to distribute traffic and ensure that the API server remains available to users.
Distributed Denial-of-Service (DDoS) protection services help to mitigate the risk of DDoS attacks by identifying and blocking malicious traffic originating from multiple different IPs, before it reaches the API server. Developers should use DDoS protection services to ensure that the API server remains available to legitimate users and protect against DDoS attacks. While Approov isn’t a replacement for a DDoS solution it can help you reducing the load of the API server, because the Approov token check occurs as soon as possible in the life-cycle of an API request, thus any request without an Approov-Token in the header can be immediately rejected, which allows more room to process legit requests from the mobile application.
By implementing these best practices, developers can protect against DDoS attacks, ensure the availability of the API server, and reduce the risk of a loss of service to users.
API security testing is an important step in ensuring the security and integrity of an API. This process involves a range of testing techniques and methodologies that aim to identify and address potential security vulnerabilities and weaknesses in the API implementation. Here are some best practices for API security testing:
Perform regular vulnerability scans on your API to identify potential vulnerabilities, such as outdated software, configuration issues, or exposed APIs.
Conduct penetration testing to simulate real-world attacks and identify potential security weaknesses that may not be detected by vulnerability scanning. Penetration testing should be performed by skilled and experienced professionals who can identify potential security issues and provide recommendations for remediation.
Fuzz testing involves sending random and unexpected data to an API to identify potential security vulnerabilities. This type of testing can help to identify security flaws such as buffer overflows or input validation issues.
Test the authentication and authorization mechanisms of your API to ensure that they are working as intended and that they are secure against common attacks such as credential stuffing and brute-force attacks.
Test the configuration settings of your API to ensure that they are secure and compliant with industry standards such as the OWASP API Security Top 10.
Test your API against relevant compliance frameworks for your business, such as HIPAA, PCI DSS, or GDPR to ensure that it meets the relevant security and privacy standards.
In summary, API security testing is a critical aspect of ensuring the security of an API. By following these best practices, developers can identify and address potential security vulnerabilities and ensure that their APIs are secure and resilient against attacks.
To guarantee the security of mobile APIs, developers should implement the best security practices that mitigate risks and include robust security measures that meet and exceed the minimum requirements to address the OWASP API Top 10 security threats. A way to enhance the security of APIs beyond the OWASP standards is to employ Remote Mobile App Attestation for locking down the API server with authentic instances of the mobile app.
Implementing Approov's remote mobile app attestation can protect even a vulnerable API from attacks by allowing only genuine instances of the mobile app that pass the attestation process to receive valid Approov tokens to add to the header of each API request. This improves the security of the API and prevents any unauthorized attempts to access it when such a token isn’t present in the header of the API request, is invalid or expired, allowing API developers to address vulnerabilities without worrying about them being actively exploited by attackers.
By making API security a priority and implementing these measures, developers can greatly improve the security and resilience of their APIs, thereby protecting users, businesses, data, and the reputation of their mobile app and company. On the contrary, poor API security can lead to significant data breaches that will damage the company's reputation, which will inevitably translate to a huge financial impact in the business.
After becoming familiar with API security best practices, we encourage you to explore our other article on Mobile App Security Best Practices, where you can discover the recommended security measures for securing mobile applications.