π Summary
APIs are everywhere β they power mobile apps, web services, and cloud-native systems.
But APIs are also one of the most common attack surfaces in modern software.
The OWASP API Security Top 10 (2021) is a developer-focused guide that explains the most critical API security risks.
π In this blog, we will:
- β Go through each of the 10 risks (A01βA10)
- π Explain what they mean in developer terms
- π Show real-world scenarios and how attacks happen
- π οΈ Outline solutions across multiple layers (code, infra, design)
- π» Provide Java (Spring Boot) and AWS examples
- π§© Highlight design patterns that help mitigate risks
- π Share lessons from real incidents
π― The goal is simple:
Help developers design and build secure APIs without slowing down delivery.
π What is OWASP API Security Top 10 (2021)?
The Open Web Application Security Project (OWASP) is a global non-profit community that provides trusted guidance on secure software practices.
Its API Security Top 10 highlights the most critical categories of API risks developers must understand.
The 2021 edition is the latest, using codes A01βA10, and is widely adopted as a standard reference by:
- π©βπ» Developers
- ποΈ Architects
- π΅οΈ Auditors and Security Reviewers
π Quick Navigation
- A01 β Broken Access Control
- A02 β Cryptographic Failures
- A03 β Injection
- A04 β Insecure Design
- A05 β Security Misconfiguration
- A06 β Vulnerable and Outdated Components
- A07 β Identification and Authentication Failures
- A08 β Software and Data Integrity Failures
- A09 β Logging and Monitoring Failures
- A10 β Server-Side Request Forgery (SSRF)
1. A01:2021 β Broken Access Control
π Explanation
Broken Access Control means users can perform actions or access information they are not authorized for.
For example, a customer may change an account ID in the request and access another customerβs account.
This happens when applications do not consistently enforce restrictions.
Proper security requires:
- Role-Based Access Control (RBAC): Broad permissions grouped by user roles
- Attribute-Based Access Control (ABAC): Finer-grained checks based on user or resource attributes such as ownership or department
π Notes & Tools
- Insecure Direct Object Reference (IDOR): Exploiting predictable identifiers in API requests
- Role-Based Access Control (RBAC): Permissions mapped to roles such as Administrator, Customer, Auditor
- Attribute-Based Access Control (ABAC): Permissions based on user or resource attributes (for example, owner ID, branch)
- Amazon Cognito / Keycloak: Identity providers that issue JWTs with roles and attributes to enforce both role-based and attribute-based access control
π₯ Example Scenario
A banking API endpoint:
/accounts/{id}
π Customers can change the id
in the URL and view another personβs account because the application does not check ownership.
π οΈ Solutions
- Application level: Enforce role-based access control (RBAC) and attribute-based access control (ABAC) using claims in JWTs
- Infrastructure level: API Gateway validates tokens before backend services
- Database level: Use row-level security (restrict records by ownerId or tenantId)
π» Code (Spring Boot)
@GetMapping("/accounts/{id}")
@PreAuthorize("hasRole('ADMIN') || #id == authentication.name")
public Account get(@PathVariable String id){
// Fetch account only if user is ADMIN or owner
return accountService.findById(id);
}
@Bean
Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuth() {
return jwt -> {
var auths = new ArrayList<GrantedAuthority>();
// Map roles from JWT claim
jwt.getClaimAsStringList("roles").forEach(r ->
auths.add(new SimpleGrantedAuthority("ROLE_" + r)));
// Map scopes from JWT claim
jwt.getClaimAsStringList("scope").forEach(s ->
auths.add(new SimpleGrantedAuthority("SCOPE_" + s)));
return new JwtAuthenticationToken(jwt, auths, jwt.getSubject());
};
}
π¨ Design Pattern
Strategy Pattern β Choose between role-based access control (RBAC) or attribute-based access control (ABAC) strategies dynamically.
β Benefits
- Prevents unauthorized data access
- Ensures consistent enforcement across systems
- Builds stronger trust with users
π¨ Real Incidents
Facebook (2019) β A bug in the photo API exposed unpublished and private photos of 6.8M users to third-party apps because permissions were overly broad and access control checks failed.
Instagram (2020) β An authorization flaw allowed attackers to retrieve private user account details by manipulating user IDs in API requests, bypassing ownership checks and exposing sensitive profile information.
Uber (2016) β Weak internal access controls gave employees broad visibility into rider trip data. Overly permissive systems lacked proper segregation of duties and failed to enforce strict authorization boundaries.
Snapchat (2014) β Public API flaw allowed enumeration of usernames and phone numbers, exposing 4.6M accounts. Missing rate limiting and insufficient authorization checks enabled attackers to harvest data at scale.
Microsoft Power Apps (2021) β Misconfigured default OData API settings exposed 38M records including personal and health data. Insecure defaults allowed anonymous public access to sensitive information across multiple organizations.
2. A02:2021 β Cryptographic Failures
π Explanation
Cryptographic failures expose sensitive data when encryption is missing, weak, or misused.
Common mistakes include:
- Transmitting data over Hypertext Transfer Protocol (HTTP) instead of Hypertext Transfer Protocol Secure (HTTPS)
- Storing passwords in plain text
- Failing to rotate keys
Attackers can intercept data, steal secrets, or modify information. Protecting data requires encryption in transit and at rest, and secure storage of secrets.
π Notes & Tools
- Transport Layer Security (TLS): Encrypts data in transit
- Mutual Transport Layer Security (mTLS): Authenticates both client and server
- AWS Key Management Service (KMS): Manages encryption keys and rotation
- AWS Secrets Manager / HashiCorp Vault: Secure storage and automatic rotation of secrets
- BCrypt: Strong hashing algorithm for securely storing passwords
π₯ Example Scenario
An API transmits login credentials over plain HTTP.
Attackers on the same Wi-Fi capture usernames and passwords because the connection is unencrypted.
π οΈ Solutions
- Application level: Hash passwords with BCrypt; never log sensitive data
- Infrastructure level: Use AWS Key Management Service (KMS) to encrypt storage; store secrets in Secrets Manager
- Network level: Enforce TLS 1.2+ and configure HTTP Strict Transport Security (HSTS)
π» Code (Spring Boot + AWS)
resource "aws_kms_key" "cust" {
enable_key_rotation = true
}
resource "aws_db_instance" "rds" {
storage_encrypted = true
kms_key_id = aws_kms_key.cust.arn
}
http.requiresChannel(c -> c.anyRequest().requiresSecure())
.headers(h -> h.httpStrictTransportSecurity(
hs -> hs.maxAgeInSeconds(31536000)));
PasswordEncoder enc = new BCryptPasswordEncoder();
user.setPassword(enc.encode(rawPassword));
π¨ Design Pattern
Facade Pattern β Centralize all encryption and hashing logic behind a single interface to ensure consistency across services.
β Benefits
- Prevents sensitive data leaks
- Protects communications from eavesdropping
- Reduces risk of stolen credentials
π¨ Real Incidents
Equifax (2017) β Poor encryption and unpatched systems led to a breach of 147 million records, including social security numbers and financial data.
Yahoo (2013β2014) β Weak cryptography and stolen credentials resulted in breaches of over 3 billion accounts, exposing email content and personal information.
Heartbleed (2014) β A flaw in OpenSSLβs implementation of TLS allowed attackers to read server memory and extract private keys.
Marriott (2018) β Inadequate cryptographic practices contributed to exposure of 500 million customer records, including passport and payment details.
Panera Bread (2018) β An API exposed customer data such as emails and loyalty card numbers because sensitive endpoints were not secured with HTTPS.
3. A03:2021 β Injection
π Explanation
Injection occurs when untrusted input is executed as part of a command or query.
Classic examples include:
- SQL Injection
- NoSQL Injection
- Command Injection
Attackers manipulate input to change the behavior of queries, retrieve unauthorized data, or run arbitrary commands.
π Notes & Tools
- Parameterized Queries: Prevent inputs from being executed as code
-
Input Validation: Enforce data rules with annotations such as
@Valid
- Web Application Firewall (WAF): Detect and block common injection payloads
π₯ Example Scenario
A login form concatenates user input into a SQL query.
Input like ' OR '1'='1
bypasses authentication and returns all users.
π οΈ Solutions
- Application level: Use parameterized queries and validate all inputs
- Infrastructure level: Deploy a Web Application Firewall (WAF) to detect injection attempts
- Database level: Run queries with least-privilege accounts to limit damage
π» Code (Spring Boot + Java)
@Query("select u from User u where u.username=:u and u.tenantId=:t")
User find(@Param("u") String username, @Param("t") String tenantId);
record LoanReq(@NotBlank String custId, @Positive BigDecimal amt) {}
@PostMapping("/loan")
void loan(@Valid @RequestBody LoanReq req) {
// Business logic for loan creation
}
π¨ Design Pattern
Builder Pattern β Construct queries safely step by step, ensuring that user inputs are always treated as data, not executable code.
β Benefits
- Eliminates one of the most common attack methods
- Ensures inputs are consistently treated as data, not code
- Protects both SQL and NoSQL databases
π¨ Real Incidents
Sony Pictures (2011) β SQL Injection attack leaked millions of records, including customer details and sensitive company data.
TalkTalk (2015) β SQL Injection exposed customer personal data and financial information of over 150,000 users.
Heartland Payment Systems (2008) β SQL Injection exploited payment systems, resulting in the theft of 130 million credit card numbers.
British Airways (2018) β Poor input handling on the airlineβs website led to customer data exposure, including names, travel information, and payment details.
Tesla (2018) β A NoSQL Injection vulnerability exposed internal cloud resources, giving attackers the ability to run malicious code and mine cryptocurrency.
4. A04:2021 β Insecure Design
π Explanation
Insecure Design refers to weaknesses in the applicationβs workflow or architecture.
Even if the code is written securely, poor design can allow attacks such as brute force login attempts, replay attacks, or missing rate limiting.
A secure design must consider abuse cases and build protections into workflows before implementation.
π Notes & Tools
- Brute Force Protection: Limit repeated login attempts to stop password guessing
- Replay Protection: Use nonces or timestamps to prevent request reuse
- Multi-Factor Authentication (MFA): Add a second factor for sensitive operations
- API Gateway Rate Limits: Control excessive traffic to protect backends
π₯ Example Scenario
A login API allows unlimited login attempts.
Attackers run automated bots to try millions of passwords until one succeeds, gaining unauthorized access.
π οΈ Solutions
- Application level: Add Multi-Factor Authentication (MFA) and enforce unique nonces for sensitive actions
- Infrastructure level: Use API Gateway or Web Application Firewall (WAF) to rate limit requests
- Network level: Block Internet Protocol (IP) addresses with repeated failed attempts
π» Code (Infrastructure Example)
rate_based_statement {
limit = 100
aggregate_key_type = "IP"
}
π¨ Design Pattern
Template Method Pattern β Define secure steps in workflows (for example: Login β Multi-Factor Authentication β Success).
β Benefits
- Reduces risks by embedding security into workflows
- Protects against brute force and replay attacks
- Ensures sensitive operations always follow strict, secure steps
π¨ Real Incidents
LinkedIn (2012) β Weak password protection and missing brute force defenses allowed attackers to steal 6.5 million password hashes from the social networking platform.
Apple iCloud (2014) β Lack of strong rate limiting enabled brute force attacks on celebrity accounts, leading to leaks of private photos.
PlayStation Network (2011) β Insecure design and inadequate protection layers caused one of the largest breaches in gaming history, exposing personal and payment data of 77 million accounts.
OWASP Juice Shop (Ongoing) β Training application intentionally demonstrates insecure design flaws, such as weak workflows and missing rate limiting, to highlight how insecure patterns are exploited in practice.
Coinbase (2019) β A design flaw allowed replay of valid requests, potentially enabling attackers to repeat transactions or actions without detection.
5. A05:2021 β Security Misconfiguration
π Explanation
Security misconfigurations are among the most common issues.
Examples include:
- Open ports
- Unnecessary services
- Default credentials
- Overly broad Cross-Origin Resource Sharing (CORS) settings
- Missing security headers
They leave APIs vulnerable even when the code itself is correct.
π Notes & Tools
- Cross-Origin Resource Sharing (CORS) Policy: Restrict requests to trusted domains
- Security Headers: Add HTTP Strict Transport Security (HSTS), X-Content-Type-Options, and others
- AWS Config: Continuously checks resources against security rules
π₯ Example Scenario
An API allows Cross-Origin Resource Sharing (CORS) requests from any origin (*
).
Malicious websites can send API requests on behalf of logged-in users, stealing their data or performing unauthorized actions.
π οΈ Solutions
- Application level: Configure strict Cross-Origin Resource Sharing (CORS) policies and enable standard security headers
- Infrastructure level: Use AWS Config to enforce security baselines across cloud resources
- Network level: Restrict open ports using Security Groups or firewall rules
π» Code (Spring Boot Example)
@Bean
WebMvcConfigurer cors() {
return r -> r.addMapping("/**")
.allowedOrigins("https://bank.com")
.allowedMethods("GET", "POST")
.allowCredentials(true);
}
π¨ Design Pattern
Facade Pattern β Centralize configuration in one layer to ensure consistency across all services.
β Benefits
- Prevents attackers from exploiting weak defaults
- Ensures secure settings across environments
- Reduces risk of accidental data exposure
π¨ Real Incidents
Capital One (2019) β Misconfigured AWS firewall exposed 100 million records, including credit card applications and customer data.
Microsoft Power Apps (2021) β Misconfigured API settings exposed 38 million records across multiple organizations, including government and healthcare.
NASA (2018) β Misconfigurations in cloud and internal systems exposed sensitive project data and credentials.
Verizon (2017) β An open Amazon Simple Storage Service (S3) bucket exposed millions of customer records, including call center logs.
Accenture (2017) β Misconfigured cloud storage exposed internal company data and access credentials publicly on the internet.
6. A06:2021 β Vulnerable and Outdated Components
π Explanation
This risk arises when applications rely on outdated libraries, frameworks, or runtime environments with known security flaws.
Attackers exploit these weaknesses even if your own code is secure.
Common issues include:
- Ignoring dependency updates
- Using unpatched container images
- Failing to track the software supply chain
π Notes & Tools
- Software Composition Analysis (SCA): Tools such as OWASP Dependency-Check or Snyk scan dependencies for known vulnerabilities
- Software Bill of Materials (SBOM): A complete list of all components; CycloneDX is a standard format
- Immutable Images: Rebuild container images regularly to include the latest security patches
π₯ Example Scenario
A banking application continues using the vulnerable Log4j library.
Attackers exploit the Log4Shell flaw to execute remote code on the server.
π οΈ Solutions
- Application level: Use Software Composition Analysis (SCA) tools in Continuous Integration / Continuous Delivery (CI/CD) pipelines to detect vulnerable libraries
- Infrastructure level: Build golden Amazon Machine Images (AMIs) or Docker images and update them regularly
- Process level: Generate Software Bill of Materials (SBOMs) and break builds when critical Common Vulnerabilities and Exposures (CVEs) are found
π» Code (Maven Example)
mvn org.owasp:dependency-check-maven:check
π¨ Design Pattern
Observer Pattern β React automatically when vulnerabilities are discovered (for example, pipeline alerts trigger build failures).
β Benefits
- Prevents exploitation of known flaws
- Keeps applications aligned with security patches
- Improves visibility into dependencies
π¨ Real Incidents
Log4Shell (2021) β Vulnerability in Log4j impacted millions of systems worldwide, enabling remote code execution.
Equifax (2017) β Failure to patch an Apache Struts vulnerability led to a massive breach, exposing personal data of 147 million people.
Heartbleed (2014) β A flaw in outdated OpenSSL versions allowed attackers to read server memory and steal private keys.
Drupalgeddon (2014) β A critical vulnerability in the Drupal content management system was widely exploited when websites failed to update promptly.
WordPress Plugins (Multiple Years) β Numerous unpatched plugins have caused widespread compromises of websites running WordPress.
7. A07:2021 β Identification and Authentication Failures
π Explanation
Weak authentication or mismanaged sessions allow attackers to impersonate users.
Examples include:
- Long-lived tokens
- Missing validation of token claims
- Weak passwords
- Using Basic Authentication between services
Secure APIs require strong identity validation, careful token management, and secure service-to-service authentication.
π Notes & Tools
- OpenID Connect (OIDC): An identity layer built on top of OAuth 2.0
- JSON Web Tokens (JWT): Secure tokens carrying claims, which must always be validated
- Mutual Transport Layer Security (mTLS): Ensures services authenticate and trust each other
- Amazon Cognito / Keycloak: Platforms that manage users, tokens, and Multi-Factor Authentication (MFA)
π₯ Example Scenario
An API issues JWTs valid for 24 hours without validating audience or expiry.
If stolen, attackers can impersonate users for a full day.
π οΈ Solutions
- Application level: Validate token issuer, audience, and expiry. Use short-lived tokens
- Infrastructure level: Use mTLS between services
- Gateway level: Enforce token validation at the API Gateway
π» Code (Java Example)
JwtDecoder dec = NimbusJwtDecoder.withJwkSetUri(jwksUri).build();
dec.setJwtValidator(new JwtClaimValidator<>("aud", aud -> aud.contains("api://svc")));
π¨ Design Pattern
Decorator Pattern β Enrich tokens with roles or scopes during validation to strengthen identity checks.
β Benefits
- Stops impersonation from stolen tokens
- Ensures only valid, trusted sessions are used
- Strengthens identity handling across systems
π¨ Real Incidents
Uber (2016) β Authentication failures exposed driver and rider data, highlighting weak internal token management.
Microsoft (2021) β Token misconfigurations in Azure Active Directory enabled exploits that allowed attackers to escalate privileges.
Facebook (2018) β A flaw in access tokens exposed 50 million accounts, allowing attackers to take over user sessions.
Instagram (2019) β API flaws exposed session tokens, leaving user accounts vulnerable to hijacking.
Google+ (2018) β Bugs in token handling exposed user data, ultimately contributing to the shutdown of the platform.
8. A08:2021 β Software and Data Integrity Failures
π Explanation
This risk arises when code, dependencies, or deployment pipelines are tampered with.
If APIs rely on unsigned packages, compromised container images, or unverified updates, attackers can inject malicious code into production systems.
π Notes & Tools
- Cosign: Tool to sign and verify container images
- Open Policy Agent (OPA): Prevents unsigned or unverified resources from being deployed
- Argo Continuous Delivery (Argo CD) with GitOps: Ensures deployments come from trusted Git repositories with full traceability
π₯ Example Scenario
An attacker pushes a malicious Docker image to a registry.
The Kubernetes cluster deploys it without verification, running untrusted code in production.
π οΈ Solutions
- Pipeline level: Sign all container images with Cosign
- Cluster level: Use Open Policy Agent (OPA) Gatekeeper to block unsigned resources
- Process level: Adopt GitOps practices to ensure deployments come only from trusted repositories
π» Code
cosign sign $ECR/app:1.2.3
π¨ Design Pattern
Proxy Pattern β Admission controllers act as intermediaries that intercept and block unverified deployments before they reach production.
β Benefits
- Prevents supply chain attacks
- Ensures only trusted code runs in production
- Adds accountability and traceability to deployments
π¨ Real Incidents
SolarWinds (2020) β A supply chain compromise inserted malicious code into software updates, impacting thousands of organizations worldwide.
Codecov (2021) β A malicious update to the Codecov Bash uploader exfiltrated credentials and tokens from customer environments for months before detection.
Event-Stream (2018) β A popular Node Package Manager (NPM) library was backdoored, harvesting cryptocurrency wallet data from applications using the dependency.
Asus Live Update (2019) β Attackers distributed signed malware through Asusβs official Live Update utility, compromising hundreds of thousands of devices.
PHP Git Server (2021) β A backdoored commit was briefly added to the official PHP source code repository, potentially impacting all downstream deployments.
9. A09:2021 β Logging and Monitoring Failures
π Explanation
Without proper logging and monitoring, attacks go undetected.
APIs may fail to log failed login attempts, unusual traffic, or sensitive actions.
Without alerts, security teams cannot respond quickly, allowing attackers to persist undetected for months.
π Notes & Tools
- Security Information and Event Management (SIEM): Centralize and analyze logs (examples: Splunk, ELK stack, AWS Security Hub)
- AWS GuardDuty: Detects anomalies in logs and network traffic
- Trace Identifiers (Trace IDs): Correlate logs across distributed services
π₯ Example Scenario
A login API does not log failed attempts.
Attackers use brute force techniques for months without detection.
π οΈ Solutions
- Application level: Log authentication attempts and assign trace identifiers (Trace IDs)
- Infrastructure level: Centralize logs in Amazon CloudWatch or an ELK stack
- Monitoring level: Use AWS GuardDuty or similar tools for anomaly alerts
π» Code (Java Example)
@EventListener
void onFail(AbstractAuthenticationFailureEvent e){
log.warn("auth_fail user={} reason={}",
e.getAuthentication().getName(), e.getException().getMessage());
}
π¨ Design Pattern
Observer Pattern β Events trigger logging and alerting actions automatically.
β Benefits
- Detects attacks early
- Enables forensic investigation
- Improves operational visibility
π¨ Real Incidents
- Equifax (2017) β Delayed detection of exploitation worsened the impact of an already critical data breach.
- Target (2013) β Security alerts were ignored, allowing the breach to persist for weeks.
- British Airways (2018) β Poor logging delayed discovery of data theft, exposing hundreds of thousands of customer records.
- SolarWinds (2020) β Weak monitoring allowed the supply chain attack to persist undetected for months.
- Capital One (2019) β Logs eventually helped investigators trace the AWS metadata breach.
10. A10:2021 β Server-Side Request Forgery (SSRF)
π Explanation
Server-Side Request Forgery (SSRF) occurs when an API makes requests to URLs supplied by users without validation.
Attackers can trick servers into connecting to internal services or cloud metadata endpoints, stealing credentials or bypassing firewalls.
π Notes & Tools
- AWS Instance Metadata Service v2 (IMDSv2): Requires a session token, mitigating metadata theft
- Kubernetes NetworkPolicy: Blocks outbound requests to sensitive IP ranges
- Outbound Proxy: Centralizes and filters all outgoing requests
π₯ Example Scenario
An API fetches files from a user-supplied URL.
An attacker requests http://169.254.169.254/
and retrieves AWS credentials from the metadata service.
π οΈ Solutions
- Application level: Validate URLs and allowlist only trusted partner domains
- Network level: Block internal ranges using Kubernetes NetworkPolicy
- Cloud level: Enforce AWS IMDSv2 for all instances
π» Code (Java Example)
String host = InetAddress.getByName(new URL(req.url()).getHost()).getHostAddress();
if (host.startsWith("169.254.") || !ALLOWED.contains(host))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
π¨ Design Pattern
Chain of Responsibility Pattern β Multiple validation steps are applied to outbound requests, ensuring only safe traffic is allowed.
β Benefits
- Stops attackers from abusing internal networks
- Protects cloud metadata services
- Ensures outbound calls are controlled and secure
π¨ Real Incidents
- Capital One (2019) β Server-Side Request Forgery (SSRF) exploited AWS metadata endpoint, exposing 100 million records.
- Tesla Cloud (2018) β Server-Side Request Forgery (SSRF) allowed attackers to access cloud systems and run unauthorized cryptocurrency mining.
- Alibaba Cloud (2020) β Server-Side Request Forgery (SSRF) flaws exposed internal cloud services of customers.
- Microsoft Azure (2017) β Server-Side Request Forgery (SSRF) in services exposed sensitive credentials from metadata endpoints.
- Jira (2019) β Server-Side Request Forgery (SSRF) vulnerability in Atlassian Jira exposed internal customer data.
π Final Takeaways
- Treat security as a design constraint, not an afterthought.
- Apply layered defenses: code, infrastructure, and process.
- Bake controls into pipelines and platforms so they are hard to bypass.
- Keep documentation and runbooks close to the code so teams can respond fast.
Bottom line: Your APIs are the front door to your business β build them to be safe by default and resilient when things go wrong.
Use this guide as a checklist for design reviews, threat modeling, and production readiness of your APIs.
Top comments (0)