AlgoMaster Logo

API Security: A Complete Guide

Last Updated: January 10, 2026

Ashish

Ashish Pratap Singh

API Security: A Complete Guide

Your API is the front door to your application. And just like a physical storefront, if you leave it unlocked, someone will eventually walk in uninvited.

APIs have become the backbone of modern software. Mobile apps, web applications, IoT devices, and microservices all communicate through APIs. This widespread adoption makes them an attractive target for attackers. A single vulnerable endpoint can expose sensitive user data, grant unauthorized access to systems, or bring down your entire service.

The consequences of poor API security are severe and well-documented. In 2023, the T-Mobile API breach exposed data of 37 million customers through a vulnerable endpoint that lacked proper access controls. The Optus breach in Australia leaked 10 million records through an unauthenticated API that was accidentally left exposed to the internet. These incidents are not outliers. According to Salt Security's 2023 State of API Security report, API attacks increased by 400% in the months leading up to the study. As organizations expose more functionality through APIs, attackers have shifted their focus accordingly.

This guide walks through the complete landscape of API security:

  • Why APIs are uniquely vulnerable to attack
  • The OWASP API Security Top 10 risks and how to mitigate them
  • Authentication mechanisms and when to use each
  • Authorization strategies from RBAC to ABAC
  • Common attack vectors with practical defenses
  • Building defense in depth with multiple security layers

By the end, you will have a practical framework for securing your APIs against the most common threats.

1. Why APIs Are a Prime Target

Understanding why APIs attract attackers helps you think like them and build better defenses.

Traditional web applications present a user interface that filters and controls what data users can access. APIs are different. They expose business logic and data directly through structured endpoints, often returning raw JSON or XML that maps closely to underlying database schemas. This fundamental difference creates unique security challenges.

The diagram above shows a typical API architecture. Multiple client types, from mobile apps to partner systems, funnel through an API gateway into backend services. Each arrow represents a potential attack vector. Each service holds sensitive data. The API gateway becomes both a chokepoint and a critical security boundary.

Here is why APIs are so attractive to attackers:

Direct Access to Data and Logic

When you browse a website, you see formatted HTML. Behind the scenes, the server decided what to show you and what to hide. APIs work differently. They return raw data, often complete database records serialized as JSON. An attacker who finds a way to query an endpoint might receive user credentials, payment information, internal system states, or anything else the API has access to. There is no UI layer to filter what gets returned.

Predictable Structure

APIs follow conventions, and conventions are predictable. REST APIs use standard HTTP methods like GET, POST, PUT, and DELETE. Resources live at predictable URLs like /users/{id} or /orders/{id}. GraphQL APIs often enable introspection by default, allowing anyone to query the complete schema. This predictability is a feature for developers but a gift for attackers. They can map your API structure quickly and start probing for weaknesses.

Expanded Attack Surface

Every endpoint is a potential entry point. A typical microservices application might expose hundreds of API endpoints across dozens of services. Each endpoint needs proper authentication, authorization, input validation, and rate limiting. Miss any of these on even one endpoint, and you have created an opening. The more endpoints you expose, the more opportunities for mistakes.

Authentication Complexity

APIs must serve wildly different client types. Mobile apps need one authentication flow. Web browsers need another. Server-to-server communication requires yet another approach. Third-party integrations add more complexity. Each client type has different security constraints, different token storage capabilities, and different threat models. Managing this complexity without introducing vulnerabilities requires careful design.

2. The OWASP API Security Top 10

The Open Web Application Security Project (OWASP) maintains a curated list of the most critical API security risks. Updated in 2023, this list reflects real-world attack patterns observed across thousands of applications. If you are building or securing APIs, this list should guide your threat modeling and code reviews.

The 2023 list differs significantly from the 2019 version. New categories like "Unrestricted Access to Sensitive Business Flows" reflect how attackers have evolved. They no longer just look for technical vulnerabilities. They exploit business logic flaws that automated tools cannot detect.

Let us examine each risk and how to mitigate it.

Let's examine each vulnerability in detail.

2.1 Broken Object Level Authorization (BOLA)

BOLA is the most common API vulnerability, and for good reason. It is easy to introduce and easy to overlook during code review.

The vulnerability occurs when an API endpoint accepts an object identifier from the client but fails to verify that the authenticated user has permission to access that specific object. The user is authenticated, so the request passes basic security checks. But authentication only proves who you are, not what you are allowed to access.

How the Attack Works

Consider an endpoint that returns a user's orders. The URL includes the user ID:

This returns orders for user 123. But what if an attacker, authenticated as user 123, changes the URL?

If the API trusts the user ID in the URL without verifying ownership, the attacker now sees user 456's orders. The authentication check passed because the token was valid. The authorization check failed because it never happened.

This attack is trivial to execute. Attackers simply iterate through IDs: 456, 457, 458, and so on. Automated tools can enumerate thousands of records in minutes. The IDOR (Insecure Direct Object Reference) variation of this attack is equally common, where attackers guess or increment object IDs like order numbers or document IDs.

Prevention

Every endpoint that accepts an object identifier must verify that the authenticated user has permission to access that specific object:

Some teams use UUIDs instead of sequential integers, thinking this provides security through obscurity. It does not. UUIDs make enumeration harder but not impossible. Leaked URLs, browser history, or logged requests can expose UUIDs. Always implement proper authorization checks regardless of ID format.

2.2 Broken Authentication

Authentication is your API's first line of defense, and it is frequently implemented incorrectly. When authentication fails, everything else becomes irrelevant. Attackers gain the ability to impersonate legitimate users.

Unlike web applications where session cookies handle most of the complexity, APIs must manage tokens, keys, and credentials directly. This creates more opportunities for mistakes.

Common Authentication Weaknesses

Several patterns repeatedly cause authentication failures:

  • Weak password policies: Allowing passwords like "password123" or not checking against known breached passwords. Attackers maintain lists of the most common passwords and try them against every account.
  • Missing brute force protection: Without rate limiting, attackers can try thousands of password combinations per second. A typical eight-character lowercase password falls in hours.
  • Credentials in URLs: API keys or tokens in query strings get logged in server access logs, browser history, and proxy caches. They leak easily.
  • Long-lived or non-expiring tokens: A stolen token that never expires gives permanent access. Tokens should expire, forcing regular re-authentication.
  • Weak token generation: Tokens generated with insufficient randomness or predictable algorithms can be guessed. Tokens should use cryptographically secure random generators.
  • Missing token validation: Some APIs validate only that a token is well-formed, not that it was actually issued by the server or has not been revoked.

Prevention

A robust authentication implementation addresses all of these concerns:

The code above includes several subtle but important details. The dummy hash check when the user does not exist prevents timing attacks that could reveal valid usernames. The short access token lifetime limits the damage from token theft. The rate limiter tracks failed attempts per username, not just per IP, to prevent distributed attacks.

2.3 Broken Object Property Level Authorization

While BOLA controls access to entire objects, this vulnerability concerns access to specific properties within objects. An API might correctly verify that you can access your own user profile but fail to restrict which fields you can modify.

This vulnerability has two variants: excessive data exposure (returning sensitive properties in responses) and mass assignment (allowing clients to modify properties they should not).

Excessive Data Exposure

An API returns more data than the client needs:

Even if the frontend only displays name and email, the full response is visible to anyone inspecting network traffic.

Mass Assignment

An API binds request data directly to internal objects without filtering:

If the API blindly updates all provided fields, the attacker just made themselves an admin with a million-dollar balance.

Prevention

Use explicit DTOs (Data Transfer Objects) that define exactly which properties are readable and writable:

Never bind request bodies directly to database entities. The few extra lines of mapping code prevent a class of vulnerabilities.

2.4 Unrestricted Resource Consumption

Every API request consumes resources: CPU cycles, memory, database connections, network bandwidth. When an API does not limit how much of these resources a single client can consume, attackers can exhaust them, denying service to legitimate users.

This vulnerability goes beyond simple denial-of-service. It also enables economic attacks against cloud-hosted APIs where compute resources translate directly to billing.

Attack Scenarios

Attackers exploit resource consumption in several ways:

  • Request flooding: Sending thousands of requests per second overwhelms the server's ability to respond. Even if each request is cheap, volume creates the problem.
  • Oversized payloads: Uploading extremely large files or sending massive JSON bodies consumes memory and bandwidth. An API that accepts unlimited file sizes invites abuse.
  • Unbounded queries: Requesting millions of records in a single query forces the database to load and serialize enormous result sets. Without pagination limits, a single request can exhaust server memory.
  • Expensive operations: Some operations are inherently costly. Complex search queries, report generation, image processing, or cryptographic operations consume disproportionate resources. Attackers trigger these repeatedly.
  • GraphQL depth attacks: GraphQL APIs that allow arbitrarily nested queries enable attackers to construct queries that explode exponentially in complexity.

Prevention

Apply limits at multiple levels:

For GraphQL APIs, implement query complexity analysis that rejects queries exceeding a threshold. For any API, set timeouts on operations so runaway queries do not consume resources indefinitely.

2.5 Broken Function Level Authorization

While BOLA concerns access to specific objects, this vulnerability concerns access to entire functions or endpoints. An API might properly restrict user data access but leave administrative endpoints unprotected.

This often happens when developers assume that hiding an endpoint is sufficient security. If users do not know the admin URL exists, they cannot access it. This assumption fails immediately when attackers start probing.

How the Attack Works

Administrative functions often follow predictable patterns:

An attacker, authenticated as a regular user, simply tries these URLs. If the API verifies only that the user is authenticated, not that they have admin privileges, the attacker gains administrative access.

Variations of this attack target API versioning (trying /api/v1/admin/ when the app uses /api/v2/) or alternate paths (/internal/, /management/, /debug/).

Prevention

Implement role-based access control at the function level, and apply it consistently:

Apply the authorization check at the controller level so new methods automatically inherit the restriction. Audit all administrative actions. Consider requiring re-authentication or MFA for sensitive operations.

The remaining five OWASP risks warrant brief discussion as well, though they appear less frequently in practice.

2.6 Unrestricted Access to Sensitive Business Flows

This is a newer category in the 2023 list. It covers attacks that abuse legitimate functionality rather than exploiting technical flaws.

Consider a ticket-purchasing API. The endpoints work correctly: authentication, authorization, rate limiting. But an attacker writes a bot that purchases all available tickets the moment they go on sale, then resells them at inflated prices. The API functions as designed, yet the business suffers.

Prevention requires understanding your business context. Implement CAPTCHA for human verification. Add purchase limits per account. Detect and block automation patterns. Monitor for unusual activity like purchasing from multiple accounts using the same payment method.

2.7 Server-Side Request Forgery (SSRF)

SSRF occurs when an API accepts URLs from clients and fetches them server-side. Attackers exploit this to reach internal systems.

We cover SSRF in detail in the Common Attack Vectors section below.

2.8 Security Misconfiguration

Default configurations are rarely secure. Debug modes, verbose error messages, unnecessary HTTP methods, missing security headers, and exposed management endpoints all fall under this category.

Prevention: Establish a security baseline configuration. Automate checks during deployment. Disable features you do not need. Keep dependencies updated.

2.9 Improper Inventory Management

Organizations often lose track of their APIs. Old API versions remain active. Development or staging endpoints are accessible from the internet. Documentation exposes internal APIs.

Prevention: Maintain an API inventory. Deprecate old versions with clear timelines. Network-segment internal APIs. Audit exposed endpoints regularly.

2.10 Unsafe Consumption of APIs

Your API might be secure, but what about the APIs you consume? Third-party APIs can be compromised, return malicious data, or behave unexpectedly.

Prevention: Validate data from external APIs. Do not trust input just because it comes from a "trusted" partner. Implement timeouts and circuit breakers. Monitor third-party API behavior.

3. Authentication Strategies

Authentication answers a simple question: who is making this request? But the answer depends on context. A server calling your API is different from a user on a mobile app, which is different from a third-party integration.

Each client type has different capabilities and constraints. A server can securely store secrets. A mobile app cannot. A web browser has cookies. An IoT device might have neither. Choosing the wrong authentication mechanism for your context creates vulnerabilities.

The following diagram shows the recommended authentication mechanism for each client type.

3.1 API Keys

API keys are the simplest form of API authentication. They are essentially long, random strings that identify the calling application. Note the distinction: API keys authenticate applications, not users. They answer "which system is calling?" rather than "which person is using this?"

When API Keys Work Well

API keys fit scenarios where user identity does not matter:

  • Server-to-server communication: Backend services calling each other. Both sides can securely store secrets, and there is no user in the loop.
  • Public APIs with usage tracking: When you want to track which applications are consuming your API and enforce rate limits per application, but individual user identity is irrelevant.
  • Internal microservices: Services within your infrastructure that need to prove they are part of your system.

When API Keys Fall Short

API keys are unsuitable when you need user-level authentication or when the client cannot securely store secrets. A mobile app or JavaScript frontend should never embed API keys because users can extract them from the binary or network traffic.

Implementation

Pass API keys in headers, not URLs. Query parameters get logged, cached, and leaked in referrer headers.

Security Best Practices

  • Treat keys as secrets: Store them encrypted. Never commit them to source control. Never log them.
  • Rotate regularly: Keys accumulate exposure over time. Rotate them periodically and immediately if compromised.
  • Scope keys narrowly: Issue different keys for different purposes. A key for reading data should not also permit writes. A production key should not work in staging.
  • Set expiration dates: Keys that never expire remain valid even after the integration that used them is gone.
  • Monitor usage: Track which keys are used, from where, and how often. Anomalies indicate compromise.

3.2 OAuth 2.0 and JWT

When users are involved, you need OAuth 2.0. This framework separates authentication (handled by an authorization server) from your API (the resource server). Users authenticate once with the authorization server and receive tokens they can use to access your API.

OAuth 2.0 defines several flows for different client types. The Authorization Code flow, shown below, works for web and mobile applications where the client can securely receive a callback.

The diagram shows the complete flow. The user never gives their credentials to your application. Instead, they authenticate directly with the authorization server. Your application receives only a token, which proves the user authenticated successfully without revealing their password.

For mobile apps, use the Authorization Code flow with PKCE (Proof Key for Code Exchange). PKCE prevents authorization code interception attacks that mobile platforms are particularly susceptible to.

JSON Web Tokens (JWT)

JWTs are the standard format for OAuth 2.0 access tokens. A JWT is a signed, Base64-encoded string containing three parts separated by dots:

The first part is the header, specifying the signing algorithm. The second part is the payload, containing claims about the user (their ID, name, roles, and token expiration). The third part is the signature, proving the token was issued by your authorization server and has not been modified.

JWTs are encoded, not encrypted. Anyone can decode the payload and read the claims. Never put sensitive information like passwords or PII in a JWT.

Validating Tokens

Every API request with a token must validate it before proceeding. Validation checks that the token is properly signed, has not expired, and was issued by a trusted authority.

JWT Best Practices

PracticeWhy It Matters
Short access token lifetime (15-60 min)Limits damage window if a token is stolen
Use refresh tokens for renewalUsers do not re-enter credentials frequently
Validate iss, aud, and exp claimsPrevents token confusion attacks
Use asymmetric signing (RS256, ES256)Resource servers verify without sharing secrets
Store tokens securelyHttpOnly cookies for web, secure storage for mobile
Never put secrets in JWT payloadJWTs are readable by anyone who has them

4. Authorization Strategies

Authentication tells you who the user is. Authorization tells you what they are allowed to do. These are distinct concerns that require separate implementations.

A common mistake is conflating the two. An authenticated request is not necessarily authorized. The user might be who they claim to be but still lack permission to perform the requested operation. Every API endpoint needs both checks: first verify identity, then verify permission.

Two authorization models dominate in practice: Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC). Understanding when to use each helps you build an authorization system that matches your requirements without unnecessary complexity.

4.1 Role-Based Access Control (RBAC)

RBAC is the workhorse of authorization. Users are assigned roles. Roles are granted permissions. When a user attempts an action, the system checks whether any of their roles has the required permission.

The diagram illustrates the indirection that makes RBAC manageable. Instead of assigning permissions directly to each user, you assign them to roles. When Alice joins the team as an admin, you assign her the Admin role. She automatically inherits all admin permissions. When permissions need to change, you modify the role definition once rather than updating every user.

Implementation

A simple RBAC implementation defines roles, permissions, and a mapping between them:

RBAC works well when authorization requirements map cleanly to roles. Most business applications fit this model. Users are admins, editors, or viewers. Permissions align with CRUD operations. The logic is straightforward to implement, test, and audit.

4.2 Attribute-Based Access Control (ABAC)

RBAC struggles when authorization depends on more than just who the user is. What if editors can only edit their own articles? What if certain operations are only allowed during business hours? What if access depends on the sensitivity level of the document?

ABAC evaluates attributes from multiple sources to make access decisions:

  • Subject attributes: Who is the user? What is their role, department, clearance level?
  • Resource attributes: What are they trying to access? Who owns it? What is its status or classification?
  • Action attributes: What operation are they attempting?
  • Environment attributes: What time is it? What is their IP address? Are they on a corporate network?

Example Policy

Consider a content management system where editors can modify their own articles, but only admins can edit published content:

This policy cannot be expressed in pure RBAC. The permission depends on both the user's role and the article's ownership and status. ABAC handles this naturally by evaluating multiple attributes together.

The tradeoff is complexity. ABAC policies can become difficult to understand, test, and audit. A change to one policy might interact unexpectedly with others.

4.3 Choosing Between RBAC and ABAC

Start with RBAC. It handles most cases and is simpler to implement correctly. Add ABAC when you need it, typically for resource ownership, time-based access, or multi-tenant isolation.

CriteriaRBACABAC
ComplexityStraightforward to implementRequires careful policy design
FlexibilityWorks for role-based permissionsHandles dynamic, context-dependent rules
PerformanceO(1) role lookupPotentially multiple attribute evaluations
AuditabilityEasy to list who has what permissionsPolicies can be harder to reason about
Best forAdmin/editor/viewer patternsOwnership, time-based, or contextual access

Many systems use both. RBAC handles broad access categories (what features can this user access?), while ABAC handles fine-grained resource access (can this user access this specific record?).

5. Common Attack Vectors

Theory is useful, but seeing how attacks work in practice makes the threats concrete. This section walks through the most common attack techniques and how to defend against them.

5.1 Injection Attacks

Injection attacks exploit the boundary between data and code. When an API constructs commands or queries by concatenating user input, attackers can inject additional commands that the interpreter executes.

SQL Injection

SQL injection remains one of the most dangerous and common vulnerabilities, despite being well understood for decades.

Consider an API that searches for users by name:

If the backend constructs the query by concatenation:

An attacker sends:

The resulting query becomes:

The database executes two statements: an empty search, then the destruction of the users table. The -- comments out the trailing quote, making the SQL syntactically valid.

More subtle attacks extract data. An attacker might use UNION to append results from other tables, or use boolean-based or time-based techniques to extract data one character at a time even when errors are not visible.

Prevention

Never construct queries by concatenating user input. Use parameterized queries (prepared statements) that separate code from data:

The parameterized version passes the user input as a parameter that the database treats as literal data. Even if the input contains SQL syntax, it is never executed.

ORMs like Hibernate or JPA typically use parameterized queries by default, but be cautious with native query features or dynamic query construction.

5.2 Cross-Site Scripting (XSS) via API

XSS traditionally targets web pages, but APIs can enable XSS when they store and return user-generated content that gets rendered in browsers.

If a user submits a comment containing <script>stealCookies()</script> and the API stores and returns it without sanitization, every user viewing that comment executes the malicious script.

Prevention

APIs should focus on proper output handling:

The Content-Type: application/json header tells the browser to treat the response as data, not HTML. The X-Content-Type-Options: nosniff header prevents browsers from ignoring the declared content type. The Content Security Policy provides additional protection by restricting what scripts can execute.

For APIs that must return HTML-renderable content, sanitize it on input using a library like OWASP Java HTML Sanitizer.

5.3 Server-Side Request Forgery (SSRF)

SSRF exploits APIs that make HTTP requests based on user-provided URLs. Instead of fetching the intended resource, attackers redirect the request to internal systems.

The diagram shows why SSRF is dangerous. The attacker cannot reach internal systems directly, but if they can make the public API fetch a URL of their choosing, the API becomes a proxy into your internal network.

Common targets include:

  • Cloud metadata endpoints: AWS, GCP, and Azure expose instance metadata at 169.254.169.254. This metadata often includes IAM credentials that grant access to cloud resources.
  • Internal services: Services that are not exposed to the internet become reachable. Internal admin panels, databases, or configuration services that assume network-level trust become accessible.
  • Localhost services: Services bound to 127.0.0.1 assume they are not network-accessible. SSRF bypasses this assumption.

Vulnerable Pattern

APIs that fetch URLs provided by users are at risk:

Prevention

Defense requires multiple layers:

When possible, use an allowlist of permitted hosts rather than trying to blocklist dangerous ones. Attackers constantly find new ways to bypass blocklists (DNS rebinding, IPv6, alternative encodings).

5.4 Mass Assignment

We covered mass assignment briefly under OWASP's Broken Object Property Level Authorization. It deserves additional attention because it is so common and so easily prevented.

The vulnerability occurs when frameworks automatically bind request data to objects:

The attacker sends:

Even if your frontend never sends isAdmin, the API accepts it.

Prevention

Always use DTOs that explicitly define which fields are acceptable:

The explicit mapping is more code, but it creates a clear contract. You see exactly which fields the API accepts and how they map to the domain model.

6. Defense in Depth

No single security measure is foolproof. Defense in depth layers multiple controls so that when one fails, others still protect your system. An attacker who bypasses your WAF still faces authentication. One who steals a token still faces authorization checks. One who finds an authorization bug still faces input validation.

The following diagram shows a typical layered architecture. Each layer adds protection and reduces the attack surface for layers behind it.

Each layer has specific responsibilities:

  • Edge protection: Filters obviously malicious traffic before it reaches your infrastructure. WAFs block common attack patterns. DDoS protection absorbs volumetric attacks.
  • Gateway: Handles cross-cutting concerns like authentication, rate limiting, and request routing. Centralizes these controls so individual services do not need to implement them.
  • Application: Implements business logic, authorization, and input validation. This is where most security decisions happen.
  • Data: Protects information at rest. Encryption, access controls, and audit logging ensure that even if other layers fail, data remains protected.

Let us examine key techniques at each layer.

6.1 Rate Limiting

Rate limiting protects your API from abuse, whether intentional (attacks) or unintentional (buggy clients, retry storms). Without rate limiting, a single client can consume resources meant for thousands.

Rate Limiting Strategies

Different algorithms offer different tradeoffs:

StrategyHow It WorksTradeoffs
Fixed WindowCount requests per calendar window (e.g., per minute)Simple but allows bursts at window edges. A client could make 100 requests at 11:59:59 and 100 more at 12:00:01.
Sliding WindowWeighted count over a rolling windowSmoother limiting, prevents edge bursts. More memory and computation.
Token BucketTokens accumulate over time up to a max. Each request consumes a token.Allows controlled bursts while enforcing average rate. Widely used.
Leaky BucketRequests queue and process at fixed rateSmoothest output rate. Can increase latency for bursty traffic.

Token bucket is the most common choice because it balances simplicity with flexibility. Here is a basic implementation:

In production, use a distributed rate limiter backed by Redis or a similar store. Rate limiting per instance does not work when requests are load-balanced across multiple servers.

6.2 Input Validation

Every piece of data from clients is potentially malicious. Validation ensures that data conforms to expected formats and constraints before your application processes it.

Validation happens at multiple levels:

Syntactic Validation

Is the data in the correct format? This is what most developers think of as validation:

  • Is the email address properly formatted?
  • Is the quantity a positive integer?
  • Is the string within length limits?
  • Does the JSON parse correctly?

Semantic Validation

Does the data make sense in context?

  • Does the referenced product ID exist?
  • Is the shipping address in a region you serve?
  • Is the requested date in the future?

Business Validation

Is the operation allowed given current state?

  • Is there sufficient stock for this order?
  • Has the user exceeded their daily limit?
  • Is this account allowed to perform this action?

Implementation Example

Validation at each level catches different problems. Syntactic validation is fast and catches obvious malformed input. Semantic validation requires database lookups but catches references to non-existent resources. Business validation enforces rules specific to your domain.

6.3 Encryption

Encryption protects data when other defenses fail. Even if an attacker gains access to your network or database, properly encrypted data remains unreadable without the keys.

Data in Transit

All API communication should use TLS. This is non-negotiable.

  • Use TLS 1.2 or 1.3: Older versions have known vulnerabilities. Configure your servers to reject TLS 1.0 and 1.1.
  • Use strong cipher suites: Prefer AEAD ciphers like AES-GCM. Disable weak ciphers like RC4 or 3DES.
  • Validate certificates: Clients should verify server certificates. Consider certificate pinning for mobile apps to prevent MITM attacks.

Data at Rest

Sensitive data in databases should be encrypted:

  • Field-level encryption: Encrypt specific sensitive fields (SSN, payment info) so they remain encrypted even if the database is compromised.
  • Envelope encryption: For large data, generate a data encryption key (DEK), encrypt the data with the DEK, then encrypt the DEK with a key encryption key (KEK) from your key management service.

Use a dedicated key management service (AWS KMS, Google Cloud KMS, HashiCorp Vault) rather than managing keys yourself. Key management is hard, and mistakes are catastrophic.

6.4 Security Headers

HTTP security headers instruct browsers on how to handle your content. They cost nothing to implement and provide meaningful protection against common attacks.

HeaderWhat It Does
Strict-Transport-SecurityTells browsers to only connect via HTTPS, even if the user types http://. Prevents protocol downgrade attacks.
X-Content-Type-Options: nosniffPrevents browsers from guessing content types. Stops attacks that rely on MIME sniffing.
X-Frame-Options: DENYPrevents your content from being embedded in iframes. Stops clickjacking attacks.
Content-Security-PolicyControls which resources can load. Mitigates XSS by restricting script sources.

For APIs, the most important are HSTS (for transport security) and Content-Type-Options (to prevent browsers from misinterpreting JSON as HTML):

These headers take minutes to add and protect against entire classes of attacks.

7. Logging and Monitoring

Prevention is important, but detection is equally critical. You cannot prevent every attack, but you can detect attacks in progress and respond before they cause major damage. Without logging and monitoring, you are flying blind.

7.1 What to Log

Security logging captures events that indicate potential attacks or policy violations. The goal is to have enough information to detect attacks, investigate incidents, and prove compliance.

Log These Security Events

  • Authentication events: Every login attempt, successful or failed. Include the username (not password), source IP, timestamp, and reason for failure.
  • Authorization failures: When authenticated users try to access resources they do not have permission for. This often indicates either a bug or an attacker probing for access.
  • Input validation failures: Requests rejected for malformed or suspicious input. Patterns in validation failures can reveal attack attempts.
  • Rate limit triggers: When clients hit rate limits. Occasional triggers are normal, but persistent triggering suggests abuse.
  • Administrative actions: Who created accounts, changed permissions, or modified configuration. These are high-value targets for attackers.

Never Log Sensitive Data

Logs themselves become an attack target. Do not create a treasure trove:

  • No credentials: Passwords, API keys, tokens, or secrets.
  • No payment data: Full credit card numbers, CVVs, or bank account details.
  • No PII beyond necessity: SSNs, health information, or other regulated data.

If you must log identifiers, use hashing or tokenization.

Structured Logging Example

7.2 Anomaly Detection

Individual log events are useful, but patterns across events reveal attacks. Anomaly detection identifies unusual behavior that might indicate an attack in progress.

Patterns That Indicate Attacks

  • Brute force attempts: Multiple failed login attempts for the same user, or many failed attempts from the same IP across different users.
  • Credential stuffing: Failed logins from many IPs using a list of username/password combinations. The per-IP rate is low, but aggregate failures are high.
  • BOLA/IDOR probing: Sequential access to object IDs (user/1, user/2, user/3...) or rapid access to many different object IDs from one client.
  • Geographic anomalies: Requests from a country where the user has never been, especially shortly after a login from a different country.
  • Time-based anomalies: API access at 3 AM from an account that normally only uses the system during business hours.
  • Error rate spikes: Sudden increase in 4xx or 5xx errors often indicates automated probing or a bug that attackers might exploit.

Alerting Strategy

Not every anomaly warrants waking someone up at 3 AM. Define severity levels:

  • Critical (immediate page): Confirmed data breach, admin account compromise, or active exploitation.
  • High (same-day response): Credential stuffing campaign, unusual admin access, or security configuration changes.
  • Medium (next business day): Pattern of authorization failures, elevated error rates, or unusual API usage patterns.
  • Low (weekly review): Minor anomalies for trend analysis.

Build runbooks for each alert type so responders know exactly what to investigate and how.

8. API Security Checklist

Use this checklist when designing and reviewing your APIs:

Authentication:

  • Strong authentication mechanism (OAuth 2.0, JWT)
  • Short-lived access tokens with refresh token rotation
  • Multi-factor authentication for sensitive operations
  • Protection against brute force attacks

Authorization:

  • Object-level authorization checks on every request
  • Function-level authorization for admin endpoints
  • Principle of least privilege

Input Handling:

  • Validate all input (type, length, format, range)
  • Use parameterized queries for database access
  • Sanitize output based on context
  • Reject unexpected content types

Transport:

  • TLS 1.2+ for all connections
  • Strong cipher suites
  • HSTS headers
  • Certificate validation

Rate Limiting:

  • Per-user and per-IP limits
  • Different limits for different endpoints
  • Graceful degradation under load

Monitoring:

  • Log security events
  • Alert on anomalies
  • Regular security audits
  • Incident response plan

References