APIs are the mechanism for data access, service integration, and business functionality. The broad landscape of API design patterns and API consumer types complicates security requirements for organizations, making it difficult to arrive at a set of best practices since it must be expansive and inclusive of many traditional security practices not yet tailored for API use cases.
Salt Security has compiled a list of API security best practices based on field experience and customer feedback. The practices are divided up into multiple security focus areas. Ideally, an organization factors in all of these practices, but your starting point will also be a factor of scope of responsibility or budget allocation. To help you track efforts and close the gaps in your API security strategy, we’ve also compiled an API Security Checklist. The full set of API security best practices also exist as a downloadable whitepaper if you’d like to research further into any of the areas of API security.
Secure API design and development
Organizations with mature security programs will often approach building applications and APIs with the mindset that security must be “built in.” Organizations will also promote secure design by establishing security requirements for engineering teams. In tandem with those requirements, the organization will also establish more detailed secure coding practices that serve as translations of high-level security requirements down to low-level specifics for a given technology stack. API security best practices for design and development include:
- Don’t reinvent the wheel with security requirements. Use well-vetted sources such as NIST and OWASP as a start, and expand on them as you grow in your API security maturity
- Be sure to include API integration. identify the overlap of security requirements for building APIs and call out the uniqueness for integration scenarios.
- Streamline threat modeling of APIs. Any threat modeling tooling you use should generate threat models that are machine parsable. You will also likely need to confine threat modeling activities to subsets of your most critical APIs. Frequency of reviews will be a byproduct of what your teams can support and how often API teams update APIs.
- Don’t skimp on the prescriptive guidance for engineering teams. Define secure coding and configuration practices that are translations of higher-level security requirements for authentication, authorization, input validation, input filtering, output escaping, error handling, encryption, and other requirements.
- Include business logic in design reviews. Ensure that you are evaluating business logic and complete API flows for susceptibility to misuse and abuse, not just exploits.
API documentation serves a range of security and non-security purposes throughout the API lifecycle. Documentation is useful for the application and API teams that are building or integrating APIs. Adequate documentation also provides benefits to a range of activities including design reviews, security testing, operations, and protection. API security best practices for documentation include:
- Use machine formats for documentation. When generating API documentation, opt for machine formats like formal API schema definitions as opposed to traditional documentation types or visual diagrams.
- Use API schema validators but acknowledge limitations. View API schema validators as a type of static analysis, much like linters or quality checkers within IDEs. They can find common issues related to syntax or missing parameters, but they are not a panacea for API security.
- Prepare for documentation discrepancies and API drift. Monitor your environments and API traffic in runtime or seek tooling that can auto-discover APIs, auto-generate schema definitions, and produce an API inventory. Production API traffic regularly deviates from intended designs.
API discovery and cataloging
An accurate API inventory is critical to all aspects of IT within the organization. Compliance, risk, and privacy teams will require API inventory, particularly as they must answer to regulatory bodies. Security teams also need API inventory so that they can have a realistic view of their organization’s attack surface and help prioritize the wide range of API security activities. Automated discovery of all API endpoints, parameters and data types is crucial. Best practices for API discovery and cataloging include:
- Discover non-production environments, not just production. Track lower environments including QA, UAT, staging, SIT, and pre-production in addition to your production environments since there may be discrepancies or exposed API endpoints in lower environments.
- Make it a habit to tag and label assets. Labeling and tagging API assets creates a type of virtuous cycle, becoming incredibly useful in supporting DevOps practices. The practice is also beneficial for other API lifecycle activities like enabling access controls or API-centric incident response.
- Include the API dependencies of your APIs. Expand beyond just homegrown APIs to also include APIs from open-source software, acquired application packages, and third-party SaaS services. The combination of built, integrated, and acquired APIs defines the digital supply chain that all organizations work within.
- Repurpose what you have as a start. Repurposing the data you collect from systems and applications can be a stopgap solution for API inventory until you are equipped to procure an API security offering with continuous discovery capabilities.
API security testing
Security testing is a significant focus area of many organizations’ API security strategies. Use traditional security testing tools to verify certain elements of an API implementation such as well-known misconfigurations or vulnerabilities, but realize these tools have limitations. No scanner is adept at parsing business logic, which also leaves organizations exposed to major forms of API abuse. Best practices for API security testing include:
- Repurpose vulnerability scanning to identify API infrastructure. Vulnerability assessment and vulnerability management (VA/VM) scanning capabilities are most useful for detecting misconfigured infrastructure or known vulnerabilities in published software. These scanners should also support ephemeral and containerized environments to adequately assess API hosting infrastructure.
- Analyze API code automatically where possible. Analyze code automatically with static analysis tools like code quality checkers and static application security testing (SAST). Scanning capability should be made available within IDEs but also run upon code commit within version control systems such as git and/or triggered as part of builds within CI/CD build pipelines.
- Run fuzzing and dynamic testing against deployed APIs. Fuzzing can help identify a wide range of exploitable conditions in APIs, but tools require significant subject matter expertise to run effectively. Dynamic application security testing (DAST) fares slightly better, but ensure that you’re testing with authenticated context and exercising APIs in the right sequence using automation scripts such as Selenium.
- Check for known vulnerable code dependencies. Dependency analyzers and software composition analysis (SCA) scanners can identify known vulnerable open-source software packages and third-party libraries in API source code, infrastructure-as-code, and container images that all play a part in the complete systems that run APIs.
- Pentest APIs periodically or as mandated by regulation. Penetration testing involves a mixture of automated and manual testing techniques. Absent compliance or regulatory requirement, it is advisable to coordinate pentest engagements quarterly, semi-annually, or annually for your most critical or exposed APIs.
- Augment testing further with bug bounties if you want more assurance. Using the “power of the crowd” with bug bounties can be useful for continuous testing and uncovering API issues. Augment security testing capacity with bug bounty programs that are public, private, and/or coordinated through a crowd-sourced platform.
Securing the front-end application, or the API client, that depends on back-end APIs for functionality and data can be useful as part of a layered security approach but has downsides. Attackers regularly decompile or disassemble client-side code to understand API endpoints and any protections you embed in front ends. Client-side code controls also aren’t feasible for direct API or machine to machine communication. API security best practices for front ends include:
- Provide security requirements for front ends. Provide internal guidance on how to exchange data securely with back-end APIs, how to authenticate users on-device, and how to persist data on-device. The OWASP Mobile ASVS (MASVS) is a good starting point for defining security requirements for mobile device platforms. Operating system vendors like Apple and Google also maintain secure coding guidance that can be useful when drafting secure coding practices.
- Presume client code and client devices are compromised. Always operate with the mindset that client applications will be reverse engineered, end user devices are compromised, and data originating from clients lacks integrity.
- Limit the data you store client-side. If you must store data client-side, use hardware-backed cryptographically secure storage to do so. APIs to interface with device-level hardware and encrypt data appropriately are provided by the respective OS vendor and should also be provided to engineering teams.
- Review client-side protection options after server-side protection. Focus first on securing back-end APIs. Client-side code and end user devices will always be prone to tampering and reverse engineering by attackers. Organizations that still pursue the path of client-side code protection must also pair code obfuscation with anti-debugging and anti-tampering techniques.
Logging and monitoring
All of the API telemetry you collect ultimately informs attack detection, incident response, and runtime protection. This logging and monitoring data is also useful for constructing baselines of what constitutes “normal” so that any outlier events can be quickly identified and resolved. API security best practices for logging and monitoring include:
- Define what elements must be logged. Account for the numerous code-level settings and infrastructure configuration as you define what information needs to be logged, at what interval, and how long it must be retained. Capture full API request and response traffic.
- Incorporate non-security logging requirements. Logging requirements should also incorporate the needs of API operations or infrastructure teams who are likely more concerned about troubleshooting availability problems and tracking uptime.
- Embrace automation for logging configuration. Don’t assume that an acquired software package or service offering has logging enabled at all or at a sufficient level of detail. A multitude of “as-code” approaches exist for infrastructure and configuration that you should consider using in your organization to help automate required logging and auditing settings.
- Embrace cloud technology. Traditional approaches for data gathering, storage, and analytics often can’t scale for even low API consumption. A modern approach may be necessary, including cloud-native design patterns and the use of cloud-enabling technologies like software defined networking and container platforms. Such an approach also doesn’t necessarily equate to public cloud service consumption, which may be restricted by company policies or regulations.
API mediation and architecture
API mediation can be achieved through several mechanisms, including network load balancers, application delivery controllers, Kubernetes ingress controllers, sidecar proxies, and service mesh ingresses. Organizations frequently deploy API management and API gateways to mediate and protect their APIs, but these technologies can only analyze API traffic per transaction. Traditional mediation mechanisms fail to provide full context, correlate activity, and identify API abuse. Best practices for API mediation and architecture include:
- Mediate APIs to improve observability and monitoring. Harvest the API telemetry from your API gateways to improve your monitoring capabilities and create amplifying effects for all API lifecycle activities.
- Mediate APIs to enforce access control. Use API gateways to enforce IP address allow/deny lists, rate limits, authentication policies, and authorization policies for API endpoints. Plan for machine consumption of APIs, such as in automation use cases or partner integration. Machine communication can be just as dominant as user consumption through client front ends, but access controls must be managed differently.
- Adopt API management for non-security use cases. Organizations sometimes reach a tipping point where they have too many APIs or too many API gateway deployments that lack standardization and centralization. If that is the case, you might opt for an APIM offering that brings a broader range of API lifecycle capabilities.
- Augment API mediation technologies with API security-focused controls. Look to purpose-built API security offerings that can provide full lifecycle security and full API context rather than repurposing traditional controls like WAF.
A primary goal of zero trust architecture (ZTA) is to enforce concepts of least privilege and restrict network access dynamically. However, connectivity must be present for APIs to function, and many API attacks still occur within trusted channels and authenticated sessions. Best practices for network security include:
- Use encrypted transport to protect the data your APIs transmit. TLS should be enabled for API endpoints to protect sensitive data in transit, ideally version 1.3 but 1.2 at a minimum. All versions of SSL should be disabled due to the number of weaknesses in the protocol or related cipher suites.
- Set IP address allow-and-deny lists for small numbers of API consumers. Mechanisms that enforce IP address allow-and-deny lists are plentiful including API gateways and network load balancers. These access lists can be useful when the set of API consumers is well-known, such as in partner integration. In practice, IP address allow-and-deny lists should be paired with behavior analysis and anomaly detection engines to be effective.
- Use dynamic rate limits and set static rate limits selectively. Rate limits can be useful for restricting consumption of APIs for a smaller set of API consumers, but these limits often become difficult to scale for larger user bases. Strive for rate limits that are dynamic, granular, and based on actual consumption patterns as opposed to generalized, static rate limits.
- Enforce network security via infrastructure, not in code. API security is not solely the responsibility of development teams. Transport protection, rate limits, and IP address allow/deny lists are almost exclusively defined in infrastructure and API mediation mechanisms.
Exposures of sensitive data can lead to significant regulatory penalties, large-scale privacy impacts, and substantial brand damage. Data security focuses help support confidentiality, integrity, and authenticity of data. Best practices for data security include:
- Use encryption selectively or as mandated by regulation. Attackers commonly exploit failed crypto implementations and misconfigurations. Application teams also make mistakes when storing key material in unsecured locations like source code or cloud storage that can be harvested by attackers. Limiting your use of encryption can mitigate some of the risk of these missteps.
- Transport protection suffices for most business and security cases. Encrypting API messages in addition to encrypted transport protocols like TLS is overkill for most organizations. This added layer of encryption requires higher degrees of effort to achieve effectively, and it can add latency or create other integration headaches.
- Always use well-vetted algorithms and encryption libraries. Maintain encryption tooling and code libraries since exploitable flaws can be uncovered over time, such as the industry saw with OpenSSL and the Heartbleed bug. NIST provides some general guidance on encryption, but you will also need to augment with specifics related to your technology stack.
- Avoid sending too much data to API clients. Always presume that front-end clients are compromised. Filter data appropriately in the back end and send only the data that is necessary for that API consumer.
- Plan for risks of scraping, data aggregation, and data inference. When attackers collect and aggregate data at scale, the result is often privacy-impacting and brand-damaging. Look for API security tooling that continuously analyzes API telemetry, analyzes behaviors, and identifies anomalous activity like scraping.
Authentication and authorization
Authentication and authorization, and by extension identity and access management (IAM), are foundational to all security domains. Be sure to account for user identities as well as machine identities as part of your API security strategy. Externalize your access controls and identity stores from code wherever possible. API security best practices for authentication and authorization include:
- Authenticate and continuously authorize API consumers. APIs are stateless, meaning that the operating environments of back-ends and front ends are often ephemeral and not guaranteed. Continuously verify whether a user or machine identity should have access to a given resource, and always presume the authenticated session might be compromised.
- Use modern authentication and authorization protocols. Use newer authentication protocols like OpenID Connect and authorization protocols. Never rely on mechanisms like basic authentication or digest authentication.
- Don’t rely on API keys as authentication. API keys are easily harvested by attackers through reverse engineering of client-side code and sniffing network traffic if keys traverse unprotected networks and the Internet. API keys should be paired with additional authentication factors such as certificates or other authentication material.
- Set reasonable idle and max session timeouts. Idle session timeout recommendations range anywhere from 5 to 30 minutes depending on exposure of the API, business criticality, and data sensitivity. Max session timeouts will depend on your business cases and risk appetite. Set timeouts for internal APIs and external APIs that balance usability and the security risk of session compromise.
- Weigh the pros and cons of session binding. binding IP addresses of API consumers to session cookies and authentication tokens can provide some security benefit but carries an unintended side effect of limiting mobility. Use of such techniques will likely vary for internal APIs and external APIs, as well as API consumer types.
- Use additional secrets in authorization flows and nonces in requests. Adding additional secrets in authentication flows helps reduce the risk of token interception and replay attacks. Common examples include anti-CSRF tokens and OAuth2 PKCE.
Any runtime protection you consider deploying should be dynamic and learn continuously. Runtime protections should encompass more than just message filtering to effectively identify misconfigurations in API infrastructure and API abuses like credential stuffing, brute forcing or scraping. API security best practices for runtime protection include:
- Look beyond traditional security controls and attack signatures. Runtime protections should extend beyond traditional technologies and make use of AI/ML and behavior analysis for API attack detection.
- Use threat protection features of your API gateways and APIM if available. Enable the threat protection rules and message filters within your API mediation technologies as a basic countermeasure. API schema can also be used to control allowable values within API requests that traverse API gateway instances and mitigate some API attacks, but your ability to do so will be bound by how consistent your API documentation processes are.
- Don’t rely on rate limiting and traffic management to stop attacks. Pair rate limiting with traffic analysis and anomaly detection so that rate limits can be set much more dynamically and adjusted per requester. Attackers will throttle their API requests to evade detection and blocking by these basic countermeasures.
- Plan for denial of service (DoS) attacks against exposed APIs. Ensure that API security solutions are able to parse API context, since API parameters and business logic are highly unique per organization, making detection of application-layer DoS for APIs very nuanced.
- Explore behavior analysis and anomaly detection. Machine-driven data analytics and behavior analysis are necessary to understand normal API consumption and identify attackers abusing APIs. As API consumption goes up, this is the only scalable approach to keep up with the flood of resulting API traffic.
Modern security operations teams must collaborate with other teams within the organization. SOC analysts often depend on application development and API protect teams who best know the application architecture and logic of APIs, which becomes critical in digital forensics and incident response. Emphasize the people and process aspects of SecOps more than technology. Best practices for security operations include:
- Account for multiple personas and work streams in the organization. Provide teams the appropriate API-related data that they need to do their job, and provide it within the tooling they use as part of their daily routine to avoid disruption.
- Create API-centric incident response playbooks. Document the organization’s digital forensics and incident response (DFIR) processes for how to respond to the inevitable, varied API attack patterns. Automate some of the workflow items as part of IR. Create IR playbooks for common API attack patterns.
- Surface actionable API events, don’t just dump data into SIEM. Consider the funnels of data being ingested into your SIEM from the specialized tools that are used across the organization. Assign priority levels based on risk-scoring and correlate API events to produce useful signals that teams can act on.
Summing up API security best practices
Enabling API security covers more than these areas of focus, and each is arguably just as critical as the next. You may opt to emphasize sets of best practices where there are already technology investments or ample headcount. You can’t do everything at once, so where do you start? Some suggestions on how to prioritize efforts within your organization include:
- Do security test your APIs, but know that you’ll also need runtime protection to catch changes that don’t go through standard build process or detect abuses that testing tools aren’t designed to find.
- Ensure that you are covering all of your environments and your digital supply chain, which is more than just the APIs mediated by your API gateways or API management suite.
- If you do nothing else, focus on runtime protection as a way to “stop the bleeding,” slow down attackers, and buy time for application and API teams.
Pick a subset of best practice areas as a starting point that are most familiar to avoid overwhelming or disrupting teams. Expand to the other sets of best practices over time to reduce gaps in your API security strategy. Ideally, you should consider purpose-built API security tooling that addresses the many elements of API security. API security tooling should be able to offer a range of capabilities throughout the lifecycle, provide the necessary context to stop attacks, and identify data exposures for your organization’s unique API business logic.