API and Distributed-Service SecurityIntroduction and ContextModern applications rarely operate as a single program. A browser or mobile client may call a REST API, a GraphQL endpoint, a WebSocket gateway, and several internal microservices. These interfaces create flexibility and scalability, but they also enlarge the attack surface. A weakness in authorization, input validation, service identity, or traffic management can expose personal data, enable account takeover, or allow an attacker to disrupt an entire system. API security is therefore broader than placing a login screen in front of an endpoint. It requires a coordinated security model covering identity, authorization, data exposure, protocol behavior, service-to-service communication, monitoring, and operational response. This chapter explains the principles and practical controls needed to secure REST, GraphQL, WebSocket, and distributed-service architectures. Learning ObjectivesBy the end of this chapter, students should be able to: - Explain the security properties required by API and microservice architectures.
- Distinguish authentication, authorization, accounting, and non-repudiation.
- Apply object-level, function-level, and property-level authorization.
- Validate schemas and constrain REST, GraphQL, and WebSocket inputs.
- Design rate limiting, gateway controls, and abuse-prevention mechanisms.
- Explain service identity, mutual TLS, token propagation, and trust boundaries.
- Identify major OWASP API Security risks and select appropriate mitigations.
- Evaluate an API security design through a practical case study.
1. The API Attack SurfaceAn API is a contract through which software exchanges requests and responses. Its attack surface includes not only URLs but also HTTP methods, headers, cookies, tokens, query parameters, request bodies, response fields, WebSocket messages, GraphQL queries, asynchronous events, and administrative interfaces. A distributed system introduces additional trust boundaries. A request may pass through a client, content delivery network, web application firewall, API gateway, identity provider, service mesh, application service, cache, database, and message broker. Each component can alter identity, enforce policy, log information, or introduce a failure. Security objectives are commonly described using the CIA triad: - Confidentiality: only authorized parties can access information.
- Integrity: data and commands cannot be changed improperly.
- Availability: authorized users can obtain service when needed.
API security also requires accountability: actions should be attributable to a principal through reliable logs and trace identifiers. These objectives can conflict. Extensive logging may improve accountability but expose secrets; aggressive filtering may improve confidentiality but hinder diagnosis. Security design is consequently a risk-management activity rather than a collection of isolated controls. Important terminology- Principal: a human, service, device, or process that can be authenticated.
- Resource: an object or capability protected by the API.
- Scope: a delegated permission, such as
orders:read. - Claim: a statement about a principal contained in a credential or token.
- Trust boundary: a point where assumptions about identity, data, or execution change.
- Control plane: interfaces used to configure or administer a system.
- Data plane: interfaces used to perform ordinary business operations.
- Idempotent operation: an operation that produces the same intended state when safely repeated.
2. Authentication and AuthorizationAuthentication answers “Who or what is making this request?” Authorization answers “What is that principal allowed to do?” Authentication without authorization is inadequate: a correctly authenticated customer may still be prohibited from reading another customer’s invoice. 2.1 Authentication modelsCommon models include: - Session cookies: the server stores session state and the browser presents a protected cookie. Cookies should use
Secure, HttpOnly, and an appropriate SameSite attribute. - OAuth 2.0 and OpenID Connect: OAuth 2.0 delegates authorization; OpenID Connect adds an identity layer. Access tokens should be audience-restricted, short-lived, and issued for specific scopes.
- API keys: useful for identifying applications or low-risk integrations, but weak as sole proof of a human identity. They require secure storage, rotation, revocation, and monitoring.
- Mutual TLS (mTLS): both client and server authenticate using certificates. It is particularly valuable for service-to-service communication.
- Signed requests: the client signs selected request components. This can provide integrity and replay protection when nonce and timestamp rules are correctly designed.
Passwords should be processed with a password-specific, adaptive hashing algorithm such as Argon2id, bcrypt, or scrypt, using unique salts and a carefully selected work factor. Passwords must not be stored using plain hashes or reversible encryption. 2.2 Authorization dimensionsAuthorization must be enforced at multiple levels: - Object-level authorization: may this principal access this specific record?
- Function-level authorization: may this principal invoke this operation?
- Property-level authorization: may this principal read or modify this field?
- Tenant-level authorization: does the object belong to the principal’s organization?
- State-level authorization: is the operation valid in the resource’s current state?
A robust policy evaluates server-side facts rather than trusting identifiers supplied by the client. For example, changing /users/874/role to /users/875/role must not grant access merely because the request format remains valid. Role-based access control (RBAC) assigns permissions to roles. Attribute-based access control (ABAC) evaluates attributes of the principal, resource, action, and context. Relationship-based access control (ReBAC) evaluates relationships such as “user is an editor of document.” RBAC is easy to understand, while ABAC and ReBAC often represent large, multi-tenant systems more accurately. A practical authorization decision can be represented conceptually as: Permit = Authenticated ∧ Policy(principal, action, resource, context) Here, Authenticated is true only when the credential is valid; Policy(...) evaluates the applicable authorization rules. This is a logical model, not a complete implementation formula. Policies must also fail closed when required attributes are missing or a policy service is unavailable. 2.3 Token validationA resource server should validate, as appropriate: - signature and trusted issuer;
- expiration and not-before times;
- audience and intended resource server;
- token type and required scopes;
- tenant or subject restrictions;
- revocation or session status where risk requires it.
The server must not accept an algorithm selected merely by an untrusted token header. Key rotation, clock tolerance, issuer configuration, and failure behavior must be specified explicitly. Tokens should contain minimal information; sensitive data should not be placed in client-readable claims merely for convenience. 3. Schema Validation and Safe Data HandlingSchema validation defines which requests and responses are structurally acceptable. It should specify data types, required fields, length limits, numerical ranges, permitted enumerations, formats, nesting depth, and maximum collection sizes. Validation has two complementary purposes: - Syntactic validation: is the input correctly formed?
- Semantic validation: is the requested action meaningful and allowed in the current business context?
For example, a date may satisfy an ISO format but still be invalid for a booking whose end precedes its start. A schema cannot replace authorization or business-rule validation. Use allowlists rather than attempting to enumerate every malicious string. Reject unknown fields when practical, especially for update operations. Distinguish “field absent” from “field set to null,” because accidental mass assignment can let attackers alter properties such as isAdmin, ownerId, or price. Output validation is also important. A service should return a deliberately designed representation rather than serializing an internal database object. Response schemas reduce accidental disclosure of passwords, internal identifiers, debugging information, and fields belonging to other tenants. Injection and canonicalizationParameterized database queries, safe command APIs, output encoding, and appropriate escaping remain necessary. Validation should occur after a well-defined canonicalization process, because equivalent encodings can otherwise bypass filters. A system should avoid repeatedly decoding or normalizing user input in different layers. The component that interprets a value should apply the rules appropriate to that interpretation. 4. Securing REST APIsREST security begins with explicit contracts. Every endpoint should document its method, authentication requirement, authorization policy, accepted content type, response schema, error behavior, and rate-limit category. Recommended practices include: - use HTTPS for every network hop carrying sensitive data;
- restrict HTTP methods and reject unexpected methods;
- validate
Content-Type and request size; - use generic error messages externally while retaining diagnostic detail in protected logs;
- implement pagination with bounded page size;
- use cursor pagination where predictable performance is needed;
- avoid exposing sequential identifiers when they create unnecessary enumeration risk;
- protect state-changing browser requests against cross-site request forgery when cookie authentication is used;
- define idempotency behavior for retried payment or order requests;
- avoid placing credentials in URLs, which are commonly logged.
An idempotency key can associate retries with a previously accepted operation. The server must define the key’s scope, retention period, request fingerprinting behavior, and response replay policy. An idempotency key is not an authorization mechanism: the request still requires normal authentication and authorization. 5. GraphQL SecurityGraphQL allows clients to specify response shape, reducing over-fetching but creating distinctive risks. A single endpoint may expose a deep query that causes expensive database work or reveals relationships a user should not traverse. Controls should include: - schema-level authorization for types and fields;
- resolver-level object and tenant authorization;
- query depth and complexity limits;
- maximum aliases and list sizes;
- request timeouts and cancellation;
- persisted or allowlisted queries for controlled clients;
- batching and caching safeguards;
- disabling detailed introspection in production when it is not required;
- redaction of sensitive error details.
Depth limiting alone is insufficient. A shallow query can still request a very large collection or trigger expensive resolvers. Complexity analysis should account for field cost, fan-out, pagination, and database operations. Authorization must occur in resolvers or an equivalent policy layer; hiding a field from documentation does not secure it. 6. WebSocket SecurityWebSockets begin with an HTTP handshake and then maintain a long-lived, bidirectional channel. The handshake must use TLS, authenticate the client, validate the expected Origin where browser clients are involved, and apply authorization before subscribing to channels or sending commands. After connection establishment, each message should be treated as untrusted input. Validate message type, schema, size, sequence, and permitted state transition. Do not assume that handshake authorization grants access to every later channel. Re-check permissions when subscriptions change and when sensitive operations are issued. Important controls include: - limits on connections per user, device, and IP address;
- idle and maximum connection lifetimes;
- heartbeat and dead-connection detection;
- per-message and aggregate bandwidth limits;
- back-pressure when consumers cannot keep up;
- safe close behavior and event logging;
- reauthentication or token refresh for long-lived sessions.
WebSocket authorization is commonly weakened when developers authenticate the handshake but fail to authorize individual subscription topics. A topic such as tenant/42/orders must be checked against the authenticated principal, not accepted as a trusted client string. 7. Rate Limiting and Availability ProtectionRate limiting controls consumption of a resource. It can protect authentication endpoints, expensive queries, database capacity, messaging systems, and business operations. Limits should be associated with meaningful identities and resources rather than IP address alone, because IPs may be shared or rotated. A token-bucket model is widely used. If tokens are added at rate r tokens per second and the bucket capacity is B tokens, a request consuming c tokens is admitted only when at least c tokens are available. The bucket refills over time but never exceeds B. This permits controlled bursts while limiting long-term consumption. The average sustainable request rate is bounded by r, while the maximum immediate burst is bounded by B tokens, subject to implementation timing and request cost. If different operations have different costs, assign a cost rather than counting every request as one. Rate limits should return a clear status such as HTTP 429, avoid leaking sensitive policy information, and provide safe retry guidance. Use layered controls: - edge or gateway limits for broad volumetric abuse;
- identity-based limits for users and applications;
- endpoint limits for expensive operations;
- concurrency limits for long-running work;
- quotas for monthly or contractual consumption;
- circuit breakers and bulkheads for downstream failure isolation.
Rate limiting cannot solve all denial-of-service threats. Upstream network protection, autoscaling, caching, queue controls, and incident response may also be required. 8. Gateways and Distributed-Service IdentityAn API gateway can terminate TLS, validate tokens, apply routing and rate policies, normalize headers, and collect metrics. It should not become the only place where authorization exists. A compromised or misconfigured internal route must not permit a service to bypass object-level authorization. In a microservice system, each service should authenticate the calling service and authorize the requested operation. Common approaches include mTLS certificates issued by an internal certificate authority, workload identities, and short-lived signed service tokens. A service should not rely solely on a client-supplied header such as X-User-Role; trusted identity context must be cryptographically protected or conveyed over an authenticated channel. Token propagation requires care. A downstream service may need the end-user identity, the calling service identity, or both. Confusing these identities can produce confused-deputy vulnerabilities, in which a privileged service performs an action on behalf of an unauthorized caller. Policies should distinguish: - subject: the end user or initiating principal;
- actor: the service making the immediate call;
- audience: the service intended to accept the credential.
A service mesh can automate mTLS, certificate rotation, traffic policy, and telemetry, but it does not understand every business authorization rule. Mesh policy and application policy are complementary. 9. OWASP API Security RisksThe OWASP API Security Top 10 provides a useful risk-oriented checklist. Important categories include: - Broken Object Level Authorization: a user accesses another user’s object by changing an identifier.
- Broken Authentication: weak credential handling, token validation, or session management enables impersonation.
- Broken Object Property Level Authorization: sensitive fields can be read or modified without permission.
- Unrestricted Resource Consumption: attackers exhaust compute, memory, bandwidth, or paid downstream resources.
- Broken Function Level Authorization: ordinary users invoke administrative functions.
- Unrestricted Access to Sensitive Business Flows: automation abuses workflows such as ticket purchases or account creation.
- Server-Side Request Forgery: the server is induced to make requests to internal or unintended destinations.
- Security Misconfiguration: unsafe defaults, permissive CORS, verbose errors, exposed documentation, or missing TLS controls create weakness.
- Improper Inventory Management: undocumented, obsolete, debug, or shadow APIs remain reachable.
- Unsafe Consumption of APIs: a service trusts third-party responses without validation, authentication, or appropriate limits.
The list is not a substitute for threat modeling. Teams should map each risk to concrete assets, attack paths, controls, tests, and monitoring signals. 10. Observability, Testing, and Incident ResponseSecurity logs should record timestamp, request or trace identifier, authenticated subject, actor service, tenant, endpoint, decision, status, latency, and relevant policy result. They should not record passwords, raw access tokens, session cookies, or unnecessary personal data. Log integrity, access control, retention, and time synchronization matter for investigations. Useful security metrics include authorization-denial rates, token-validation failures, unusual object-access patterns, GraphQL complexity rejections, WebSocket connection churn, rate-limit responses, and service-to-service authentication failures. Metrics should support detection without turning normal privacy-preserving behavior into suspicion. Testing should include: - unit tests for policy rules;
- integration tests across gateway and services;
- negative tests for object and function authorization;
- schema fuzzing and boundary tests;
- replay, token-confusion, and expiration tests;
- rate-limit and concurrency tests;
- GraphQL depth and cost tests;
- WebSocket subscription isolation tests;
- dependency and configuration scanning;
- threat modeling before major architectural changes.
Security tests should use realistic tenant boundaries. A test that only verifies “authenticated user can read an object” misses the more important question: “authenticated user from tenant A cannot read tenant B’s object.” Illustrative Case Study: Multi-Tenant Logistics PlatformBackgroundConsider FleetFlow, an illustrative logistics platform. Customers create shipments through REST, monitor vehicle locations through WebSockets, and use a GraphQL dashboard. Internal services manage identity, billing, routing, and notifications. ProblemA security review discovers that shipment URLs contain sequential identifiers. The API checks that users are logged in but does not verify shipment ownership. The GraphQL endpoint permits deeply nested queries. WebSocket clients can subscribe to any topic by supplying its name. Internal services trust a gateway-added user header, and billing retries occasionally create duplicate charges. AnalysisThe platform has broken object-level authorization, unrestricted resource consumption, broken property-level authorization, weak service identity, and an unsafe business-flow retry design. The gateway is performing authentication but is incorrectly treated as the complete authorization boundary. Approach and solutionFleetFlow introduces a centralized policy library used by each service. Every shipment query checks the subject’s tenant and relationship to the shipment. Response DTOs exclude internal routing notes and billing fields. GraphQL applies depth, cost, list-size, and timeout limits, while high-volume dashboards use persisted queries. WebSocket handshakes authenticate with short-lived tokens, validate browser origin, and authorize each subscription against the tenant and shipment relationship. Connection, message, and bandwidth limits are enforced per identity. The platform adopts mTLS for service identity and passes a signed, audience-restricted end-user context where downstream business authorization requires it. Services reject unsigned identity headers. Billing uses an idempotency key bound to the authenticated merchant, operation type, and request fingerprint. Duplicate submissions return the original operation result rather than charging again. The gateway applies broad rate limits and rejects malformed requests, while services retain object and function authorization. Logs include trace IDs, decision outcomes, and tenant context without storing tokens. OutcomeThe revised design prevents cross-tenant shipment access, limits expensive queries, isolates WebSocket channels, and makes service calls attributable. It also improves reliability by making payment retries safe. Remaining risks include compromised customer credentials, insider misuse, and volumetric attacks requiring controls beyond the application. Learning points- Authentication does not establish object ownership.
- Every protocol needs message- or resolver-level authorization.
- Gateway controls must be reinforced by service-level policy.
- Availability requires cost, concurrency, and quota controls, not only requests-per-second limits.
- Secure retries require explicit idempotency semantics.
11. Governance, Ethics, and Contemporary PracticeAPI security involves personal data, behavioral records, and potentially high-impact decisions. Data minimization, purpose limitation, retention controls, access reviews, and breach notification procedures should align with applicable privacy and cybersecurity law. Security monitoring must be proportionate and transparent; collecting excessive user telemetry creates its own privacy risk. Organizations should maintain an API inventory, ownership records, data classifications, threat models, dependency inventories, and deprecation schedules. Security requirements should be included in architecture review and the software development lifecycle rather than added immediately before release. AI-assisted coding and automated API generation can accelerate development but may reproduce insecure authorization patterns, expose secrets in prompts, or generate schemas that overexpose internal models. Generated code requires human review, tests using adversarial cases, dependency assessment, and verification that policy enforcement is present at the correct boundary. AI systems connected to APIs must receive narrowly scoped credentials and be protected against prompt injection, unauthorized tool use, and excessive autonomy. Best-Practice Design Checklist- Identify every public, partner, internal, administrative, and deprecated API.
- Use TLS and validate identity for every relevant hop.
- Separate authentication from object, function, property, and tenant authorization.
- Validate request and response schemas with bounded sizes and explicit fields.
- Apply authorization inside services, not only at the gateway.
- Use short-lived, audience-restricted credentials and rotate keys.
- Limit GraphQL depth, cost, aliases, list sizes, and execution time.
- Authenticate WebSocket handshakes and authorize each subscription and command.
- Combine rate, concurrency, quota, timeout, bulkhead, and circuit-breaker controls.
- Log security decisions safely and monitor anomalous access patterns.
- Test negative cases across tenants, roles, protocols, and failure modes.
- Remove or protect obsolete and undocumented endpoints.
Chapter SummaryAPI and distributed-service security requires defense in depth across identity, authorization, validation, availability, service communication, and observability. Authentication establishes a principal, but authorization must independently evaluate the action, resource, properties, tenant, and context. REST APIs benefit from explicit contracts, bounded inputs, safe error handling, and idempotent retry design. GraphQL requires field authorization and query-cost controls, while WebSockets require authorization throughout long-lived connections rather than only at the handshake. Gateways provide valuable edge enforcement but cannot replace service-level policy. mTLS, workload identity, audience-restricted tokens, and clear separation of subject and actor reduce confused-deputy risk. Rate limiting, concurrency controls, quotas, circuit breakers, and bulkheads protect availability. OWASP API risks provide a practical assessment framework, but effective security also depends on inventories, threat modeling, testing, privacy governance, and incident response. Key TermsAuthentication: Verification of the identity of a principal. Authorization: Decision about whether a principal may perform an action. API gateway: An edge component that routes requests and may enforce common controls. Object-level authorization: Permission checking for a particular resource instance. Function-level authorization: Permission checking for an operation or endpoint. Property-level authorization: Permission checking for individual fields or attributes. Tenant isolation: Prevention of unauthorized access across organizational boundaries. OAuth 2.0: A framework for delegated authorization. OpenID Connect: An identity layer built on OAuth 2.0. Mutual TLS: TLS in which both communicating parties authenticate with certificates. Schema validation: Checking data against defined structural and constraint rules. GraphQL resolver: Code that obtains or computes a field’s value. WebSocket: A protocol providing a persistent, bidirectional communication channel. Rate limiting: Restricting the frequency or cost of operations. Token bucket: A rate-control model allowing bounded bursts and a controlled average rate. Idempotency: Property that safe repetition produces the same intended effect. Service identity: Verifiable identity of a workload or service. Confused deputy: A privileged component induced to misuse its authority for another party. Circuit breaker: A control that temporarily stops calls to a failing dependency. Threat modeling: Structured analysis of assets, threats, trust boundaries, and mitigations. Review QuestionsShort Answer Questions- What is the difference between authentication and authorization?
- Why is object-level authorization necessary even when a user is authenticated?
- Name two controls that reduce GraphQL resource-exhaustion risk.
- Why should WebSocket messages be validated after the handshake?
- What security purpose does mutual TLS serve in a microservice system?
Long Answer Questions- Explain how RBAC, ABAC, and ReBAC differ, and identify a suitable use case for each.
- Describe a defense-in-depth design for a REST API handling sensitive multi-tenant data.
- Explain why an API gateway cannot be the sole authorization boundary in a microservice architecture.
- Discuss the security and reliability requirements for idempotent payment retries.
- Analyze the major security controls required for a production GraphQL service.
Analytical / Application Questions- A customer changes
/shipments/1204 to /shipments/1205 and receives another customer’s shipment. Identify the vulnerability, explain the missing control, and propose a test case. - A WebSocket dashboard permits subscriptions to arbitrary tenant topics. Design an authentication, authorization, validation, and rate-control solution.
- An internal service accepts a gateway-supplied
X-User-Role: admin header. Analyze the trust failure and redesign the service-identity and end-user-context flow.
Multiple Choice Questions with AnswersQuestion 1Which control directly prevents a user from reading another tenant’s record by changing an object identifier? A. Object-level authorization B. TLS certificate rotation C. Response compression D. DNS caching Correct Answer: A. Object-level authorization Question 2What is the primary purpose of audience validation on an access token? A. To increase token size B. To ensure the token is intended for the receiving service C. To make passwords unnecessary D. To permit unlimited token reuse Correct Answer: B. To ensure the token is intended for the receiving service Question 3Which GraphQL control addresses expensive queries that are shallow but request very large collections? A. Disabling TLS B. Removing all schemas C. List-size and query-cost limits D. Allowing unlimited aliases Correct Answer: C. List-size and query-cost limits Question 4Why must WebSocket subscriptions be authorized individually? A. The handshake automatically authorizes every topic B. A valid connection does not imply access to every channel C. WebSockets cannot use authentication D. Subscriptions contain no sensitive data Correct Answer: B. A valid connection does not imply access to every channel Question 5In a token-bucket rate limiter, what does bucket capacity primarily bound? A. Maximum permitted burst B. Password length C. Certificate lifetime D. Database table size Correct Answer: A. Maximum permitted burst Question 6Which mechanism most directly authenticates both sides of a service-to-service TLS connection? A. CORS B. Mutual TLS C. Pagination D. GraphQL introspection Correct Answer: B. Mutual TLS Question 7Which practice best reduces mass-assignment risk? A. Accepting every JSON property B. Serializing database objects directly C. Using explicit input and output schemas D. Trusting client-supplied roles Correct Answer: C. Using explicit input and output schemas Question 8What is a confused-deputy vulnerability? A. A service uses excessive authority on behalf of an unauthorized caller B. A client forgets a password C. A server returns compressed content D. A certificate expires normally Correct Answer: A. A service uses excessive authority on behalf of an unauthorized caller Question 9Which response is generally appropriate when a client exceeds an API rate limit? A. HTTP 429 B. HTTP 101 C. HTTP 204 D. HTTP 304 Correct Answer: A. HTTP 429 Question 10What does an idempotency key help prevent in a payment API? A. Duplicate effects from safely retried requests B. All forms of phishing C. Unauthorized TLS termination D. GraphQL schema discovery Correct Answer: A. Duplicate effects from safely retried requests
|