OWASP API Top 10 — 2023

API Security Best Practices

API Security focuses on protecting application programming interfaces from attacks and vulnerabilities. As APIs become the backbone of modern applications, securing them against common threats like broken authentication, excessive data exposure, and broken access control is critical for protecting sensitive data and business operations.

What Is API Security?

API Security encompasses the strategies, tools, and practices used to protect application programming interfaces from malicious attacks and unauthorized access. APIs are the backbone of modern applications, enabling communication between different services, mobile apps, web applications, and third-party integrations. However, this critical role also makes them attractive targets for attackers seeking to exploit vulnerabilities in authentication, authorization, data exposure, and resource consumption.

The OWASP API Security Top 10 2023 identifies the most critical API security risks that organizations face today. Unlike the OWASP Web Top 10, which focuses on web application vulnerabilities, the API Security Top 10 specifically addresses threats unique to API architectures, such as broken object level authorization (BOLA), unrestricted resource consumption, and server-side request forgery (SSRF). These vulnerabilities can lead to data breaches, unauthorized access, denial of service, and complete system compromise.

This guide covers the most prevalent API vulnerabilities including Broken Object Level Authorization (BOLA), which allows attackers to access other users' data by manipulating object IDs; Broken Authentication, where weak or missing authentication mechanisms enable unauthorized access; Excessive Data Exposure, where APIs return more information than necessary; Broken Function Level Authorization, which fails to properly enforce access controls on administrative endpoints; Mass Assignment vulnerabilities that allow attackers to modify object properties they shouldn't access; and Unrestricted Resource Consumption that can lead to denial of service through API abuse.

How It Works

1
API reconnaissance and discovery

Attackers begin by discovering available API endpoints through multiple techniques: analyzing client-side JavaScript code, examining mobile app traffic, reviewing API documentation, and testing common endpoint patterns. They use tools like Burp Suite, OWASP ZAP, or custom scripts to map the entire API surface area, identifying both public and hidden endpoints.

2
Endpoint enumeration and testing

Once endpoints are discovered, attackers systematically test each one to understand its behavior, parameters, authentication requirements, and response patterns. They examine HTTP methods (GET, POST, PUT, DELETE, PATCH), query parameters, request headers, and body structures to identify potential injection points and parameter tampering opportunities.

3
Authentication and authorization testing

Attackers test authentication mechanisms by attempting to bypass login flows, reuse tokens across different accounts, manipulate JWT claims, or exploit weak token generation. They also test authorization by accessing resources with different user contexts, attempting horizontal privilege escalation (accessing other users' data) and vertical escalation (accessing admin functions).

4
Data manipulation and parameter tampering

With knowledge of how the API works, attackers manipulate request parameters to exploit vulnerabilities. They change object IDs to access other users' resources (BOLA), add extra fields to requests to exploit mass assignment, or remove authorization headers to test if endpoints are properly protected. They also test for injection vulnerabilities by sending SQL, NoSQL, or command injection payloads.

5
Exploitation and lateral movement

Once vulnerabilities are identified, attackers exploit them to achieve their objectives: exfiltrating sensitive data through excessive data exposure, gaining unauthorized access via broken authentication, escalating privileges through function-level authorization flaws, or causing denial of service through unrestricted resource consumption. Successful exploitation often leads to deeper system compromise and lateral movement to other services.

Vulnerable Code Example

Vulnerable — Java / Spring Boot
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    // VULNERABLE: No authentication required
    // VULNERABLE: Returns full user object with sensitive fields
    // VULNERABLE: No rate limiting
    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        User user = userRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("User not found"));

        // Returns user with password hash, SSN, credit cards, etc.
        return ResponseEntity.ok(user);
    }

    // VULNERABLE: No authorization check (BOLA)
    // Any authenticated user can update any other user's data
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(
        @PathVariable Long id,
        @RequestBody User userUpdate) {

        User user = userRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("User not found"));

        // VULNERABLE: Mass assignment - accepts ALL fields from request
        // Attacker can set isAdmin=true, balance=1000000, etc.
        BeanUtils.copyProperties(userUpdate, user);

        userRepository.save(user);
        return ResponseEntity.ok(user);
    }

    // VULNERABLE: No function-level authorization
    // Regular users can access admin endpoint
    @DeleteMapping("/admin/delete/{id}")
    public ResponseEntity<?> adminDeleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
        return ResponseEntity.ok("User deleted");
    }
}

Secure Code Example

Secure — Java / Spring Boot (JWT + DTOs + Rate Limiting)
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // SECURE: JWT authentication required
    // SECURE: Rate limited to 100 requests per minute
    // SECURE: Returns DTO without sensitive fields
    @GetMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    @RateLimiter(name = "userApi", fallbackMethod = "rateLimitFallback")
    public ResponseEntity<UserDTO> getUser(
        @PathVariable Long id,
        @AuthenticationPrincipal UserPrincipal currentUser) {

        UserDTO user = userService.getUserById(id);
        return ResponseEntity.ok(user);
    }

    // SECURE: Authorization check - users can only update their own data
    // SECURE: Input validation
    // SECURE: DTO prevents mass assignment
    @PutMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<UserDTO> updateUser(
        @PathVariable Long id,
        @Valid @RequestBody UserUpdateDTO userUpdate,
        @AuthenticationPrincipal UserPrincipal currentUser) {

        // SECURE: Verify user can only update their own profile
        if (!currentUser.getId().equals(id) && !currentUser.isAdmin()) {
            throw new ForbiddenException("Cannot update other users");
        }

        // SECURE: DTO only accepts allowed fields (name, email)
        // Cannot set isAdmin, balance, etc.
        UserDTO updated = userService.updateUser(id, userUpdate);
        return ResponseEntity.ok(updated);
    }

    // SECURE: Function-level authorization - admin only
    @DeleteMapping("/admin/delete/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    @AuditLog(action = "DELETE_USER")
    public ResponseEntity<?> adminDeleteUser(
        @PathVariable Long id,
        @AuthenticationPrincipal UserPrincipal admin) {

        userService.deleteUser(id);
        return ResponseEntity.ok(Map.of("message", "User deleted"));
    }
}

// UserDTO exposes only safe fields
public class UserDTO {
    private Long id;
    private String name;
    private String email;
    private LocalDateTime createdAt;
    // password, SSN, tokens NOT included
}

// UserUpdateDTO accepts only allowed fields
public class UserUpdateDTO {
    @NotBlank @Size(max = 100)
    private String name;

    @Email @NotBlank
    private String email;
    // isAdmin, balance, etc. NOT accepted
}

Types of API Vulnerabilities

Broken Object Level Authorization (BOLA)

The most common and critical API vulnerability, also known as IDOR (Insecure Direct Object Reference). Occurs when APIs fail to verify that a user has permission to access a specific object. Attackers manipulate object IDs in API calls (e.g., changing /api/users/123 to /api/users/124) to access other users' data. BOLA is ranked #1 in OWASP API Security Top 10 2023 and has been exploited in major breaches at companies like Peloton, Experian, and Facebook.

Broken Authentication & Function-Level Auth

Encompasses two critical areas: Broken Authentication occurs when APIs use weak or missing authentication mechanisms, predictable tokens, or fail to properly validate credentials. Attackers exploit this through credential stuffing, token reuse, or bypassing authentication entirely. Broken Function-Level Authorization happens when regular users can access administrative functions because the API doesn't enforce role-based access controls. Both vulnerabilities allow unauthorized access to sensitive operations and data.

Excessive Data Exposure & Mass Assignment

Excessive Data Exposure occurs when APIs return complete data objects with sensitive fields, relying on clients to filter the data. This exposes passwords, tokens, PII, and internal system details. Mass Assignment is the opposite problem: APIs accept client input without filtering, allowing attackers to modify properties they shouldn't access. Attackers send extra fields like isAdmin: true or balance: 1000000 in requests. Both vulnerabilities stem from failing to use DTOs (Data Transfer Objects) to control exactly what data enters and exits the API.

Impact

API security vulnerabilities can have severe consequences for organizations, ranging from data breaches to complete system compromise. The impact depends on the vulnerability type, the sensitivity of the exposed data, and the privileges gained by attackers.

Unauthorized access to sensitive data

Broken Object Level Authorization and Excessive Data Exposure allow attackers to access personal information, financial records, medical data, and confidential business information belonging to other users or the organization. This can result in identity theft, financial fraud, regulatory violations (GDPR, HIPAA), and massive data breaches affecting millions of users.

Account takeover and privilege escalation

Broken Authentication allows attackers to bypass login mechanisms, steal session tokens, or reuse credentials across accounts. Mass Assignment enables privilege escalation by modifying user roles or permissions. Once authenticated with elevated privileges, attackers can access administrative functions, modify system configurations, or impersonate other users including administrators.

Data manipulation and business logic abuse

APIs with broken authorization or mass assignment vulnerabilities allow attackers to modify critical data including user profiles, financial transactions, inventory levels, or pricing information. This can lead to financial losses, corrupted business operations, fraudulent transactions, and loss of data integrity that cascades through integrated systems.

Denial of service and resource exhaustion

Unrestricted Resource Consumption vulnerabilities allow attackers to overwhelm APIs through excessive requests, large payloads, or operations that consume significant server resources. Without proper rate limiting, pagination, or resource quotas, attackers can cause service outages, degrade performance for legitimate users, or incur massive cloud computing costs through API abuse.

Prevention Checklist

Implement strong authentication and authorization

Use industry-standard authentication mechanisms like OAuth 2.0, OpenID Connect, or JWT tokens with proper signature verification. Every API endpoint must verify authentication. Implement object-level authorization checks for every request that accesses user-specific resources. Never trust client-supplied object IDs without verifying the current user owns that object. Use policy engines like OPA (Open Policy Agent) or built-in framework authorization (Spring Security, .NET Core Authorization) to enforce consistent access controls.

Enforce function-level authorization

Implement role-based access control (RBAC) or attribute-based access control (ABAC) to restrict access to administrative and sensitive functions. Use framework-provided authorization attributes like @PreAuthorize, [Authorize(Roles="Admin")], or middleware to enforce role checks. Never rely on client-side hiding of admin features. Deny access by default and explicitly grant permissions based on verified user roles or attributes.

Use DTOs for input validation and response filtering

Implement Data Transfer Objects (DTOs) to explicitly define which fields can be accepted in requests and returned in responses. This prevents excessive data exposure by ensuring sensitive fields like passwords, tokens, or internal IDs are never included in API responses. It also prevents mass assignment attacks by accepting only the specific fields defined in the DTO. Use validation frameworks like Bean Validation (Java), FluentValidation (.NET), or Joi (Node.js) to validate input DTOs.

Implement rate limiting and resource quotas

Apply rate limiting at multiple levels: per user, per IP address, and per endpoint. Use libraries like Resilience4j, AspNetCoreRateLimit, or express-rate-limit. Implement pagination for list endpoints with reasonable default and maximum page sizes. Set timeouts for long-running operations. Monitor and alert on unusual API usage patterns. Consider implementing API throttling strategies like token bucket or leaky bucket algorithms to prevent resource exhaustion attacks.

Validate and sanitize all input

Treat all API input as untrusted, including query parameters, headers, request bodies, and file uploads. Use strict input validation with allowlists rather than blocklists. Validate data types, formats, ranges, and lengths. Sanitize input to prevent injection attacks (SQL, NoSQL, OS command, LDAP). Use parameterized queries or ORMs to prevent database injection. Reject requests with unexpected or malicious content rather than attempting to sanitize them.

Use API gateways and security monitoring

Deploy an API gateway (Kong, Apigee, AWS API Gateway, Azure API Management) to centralize security controls including authentication, rate limiting, request validation, and threat detection. Implement comprehensive logging of all API requests and responses, including authentication events, authorization failures, and suspicious patterns. Use SIEM tools or API security platforms to detect anomalies, brute force attempts, and potential attacks. Conduct regular penetration testing and security assessments focused on API endpoints.

Real-World Examples

2022

Optus Data Breach

Australian telecom giant Optus suffered a massive data breach affecting 9.8 million customers due to an unauthenticated API endpoint. The API exposed customer records including names, dates of birth, phone numbers, email addresses, and physical addresses without requiring any authentication. Attackers simply enumerated customer IDs to extract data. The breach resulted in regulatory investigations, class action lawsuits, and an estimated $100 million in costs.

2021

Peloton BOLA Vulnerability

Security researcher Jan Masters discovered a critical Broken Object Level Authorization (BOLA) vulnerability in Peloton's API that exposed private user data including workout statistics, group memberships, weight, age, and gender for all users. By simply changing the user ID in API requests, any authenticated user could access other users' private profiles and activity data. The vulnerability affected millions of Peloton users before it was patched.

2018

Facebook Graph API

Facebook's Graph API suffered from excessive data exposure that enabled the Cambridge Analytica scandal. The API returned far more user data than necessary, including friends' data, and relied on third-party apps to self-police their data collection. This led to the harvesting of personal information from up to 87 million Facebook users without explicit consent. The incident resulted in a $5 billion FTC fine and fundamentally changed how Facebook's APIs expose user data.

2023

T-Mobile API Data Exposure

T-Mobile experienced a security incident where attackers exploited API vulnerabilities to access customer data including names, billing addresses, phone numbers, account numbers, and rate plans. The breach affected 37 million customers and was attributed to API security weaknesses that allowed unauthorized access to customer information systems. This was T-Mobile's eighth data breach since 2018, highlighting the ongoing challenges of securing complex API ecosystems.

Ready to Test Your Knowledge?

Put what you have learned into practice. Try identifying and fixing API security vulnerabilities in our interactive coding challenges, or explore more security guides to deepen your understanding.