Web & Application Security

Chapter 6
API, Mobile and Rich-Client Security

Advance Diploma in Cybersecurity
Web & Application Security   •   Advance Diploma

API, Mobile and Rich-Client Security

Introduction and Context

Modern applications rarely operate as a single server-rendered website. Mobile applications, single-page applications, Internet of Things devices, partner integrations, and microservices communicate through application programming interfaces (APIs). These interfaces expose business capabilities and data, making them a primary security boundary.

API security is not simply transport encryption or authentication. A secure API must establish who is calling, what that caller is permitted to do, which data may be returned, how requests are structured, how rapidly they may be made, and how abuse is detected. These concerns become more difficult when applications use REST, GraphQL, WebSocket, distributed microservices, and mobile or rich-client front ends.

This chapter applies the principles of least privilege, defence in depth, secure-by-design development, and zero-trust architecture to API ecosystems. It emphasises object-level authorisation, token abuse, excessive data exposure, rate limiting, schema validation, secure client storage, certificate validation, and automated abuse.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain the security properties and risks of REST, GraphQL, WebSocket, and microservice APIs.
  2. Distinguish authentication, authorisation, object-level authorisation, and function-level authorisation.
  3. Design controls for broken object-level authorisation, token abuse, excessive data exposure, and mass assignment.
  4. Apply schema validation, rate limiting, quotas, and abuse monitoring.
  5. Evaluate mobile and rich-client storage, transport, certificate-validation, and session designs.
  6. Develop a security testing and governance approach for API ecosystems.

1. API Security as a System Property

An API request typically passes through several layers: a client, a DNS and network path, an API gateway, an authentication service, an application service, a database or message broker, and monitoring systems. Security failure at any layer can compromise the whole transaction.

Authentication answers “Who is the caller?” Authorisation answers “What may that caller do?” Confidentiality protects data from unauthorised observation, integrity protects it from unauthorised modification, and availability ensures that legitimate users can obtain service. Non-repudiation is more difficult in distributed systems because logs, keys, clocks, and identity context must be trustworthy.

A useful security decision can be represented conceptually as:

Permit = Authenticated ∧ Authorised ∧ ValidRequest ∧ WithinPolicy

Here, Authenticated indicates that the identity has been established; Authorised indicates that the requested action is permitted for the specific resource; ValidRequest indicates syntactic and semantic validity; and WithinPolicy includes limits such as rate, device risk, location, and transaction value. This is a logical model rather than a numerical formula. All four conditions must hold; authentication alone is insufficient.

Important terminology

  • Resource: An object exposed through an API, such as an invoice, profile, or payment.
  • Object identifier: A value identifying a resource, commonly an integer, UUID, or opaque string.
  • Endpoint: A callable API operation, such as GET /accounts/42.
  • Scope: A permission associated with a token, such as payments:read.
  • Claim: A statement in a token, such as subject, issuer, audience, or expiry.
  • Schema: The permitted structure, types, constraints, and relationships of input or output data.
  • Gateway: A managed entry point that can route, authenticate, limit, and observe API traffic.
  • Rich client: A browser or desktop application that performs substantial processing locally.

2. REST Security

REST APIs commonly use HTTP methods and resource-oriented URLs. Their simplicity can create false confidence: an endpoint may be technically protected while still allowing a user to access another user’s object.

Object-level authorisation

Consider GET /api/orders/4815. The server must verify not merely that the requester is logged in, but that order 4815 belongs to the requester or is otherwise accessible under a defined business relationship. The identifier is not an authorisation decision.

A robust pattern is to enforce ownership in the data-access operation itself, for example conceptually:

SELECT * FROM orders WHERE id = :id AND owner_id = :current_user

This is stronger than retrieving by id and checking ownership later, because it reduces the chance that a future code path forgets the check. Authorisation should be performed on every request and every object, including nested resources, export functions, background jobs, and administrative interfaces.

Function-level authorisation

A low-privilege user should not gain administrative capability by changing GET to DELETE, guessing an administrator endpoint, or altering a role field. Server-side policy must define permitted operations independently of client interface controls. Deny-by-default policies and central policy enforcement reduce inconsistency.

Mass assignment and property-level exposure

Automatically binding request fields to domain objects can allow attackers to submit fields such as role, balance, or isApproved. Use explicit allow-lists for writable properties, immutable domain models, and server-controlled transitions. Responses should use dedicated view models rather than serialising database entities, thereby reducing excessive data exposure.

HTTP and REST controls

Use TLS for all traffic, including internal service calls where feasible. Validate content types, reject unexpected methods, use appropriate cache-control headers for sensitive responses, and avoid placing credentials in URLs. CORS should allow only required origins, methods, and headers; it is not an authentication mechanism. Error responses should provide useful correlation identifiers without revealing stack traces, SQL, secrets, or internal topology.

3. GraphQL Security

GraphQL allows clients to request fields through a typed schema. This can reduce over-fetching, but it introduces query-complexity and resolver-authorisation risks.

Every resolver must enforce authorisation for the object and field being returned. Protecting only the top-level query is unsafe: a permitted account query might expose a sensitive nested field. Mutations require the same validation and authorisation as REST updates.

GraphQL-specific controls include:

  • Disable or restrict introspection in production when it reveals sensitive schema detail; do not treat concealment as the primary defence.
  • Enforce maximum query depth and calculated complexity.
  • Limit aliases and batching that can multiply resolver work.
  • Apply pagination with bounded page sizes.
  • Set execution timeouts and resource budgets.
  • Validate variables and scalar values against business constraints.
  • Prevent resolver-induced N+1 database queries through controlled batching.
  • Log operation names, caller identity, complexity, outcome, and latency while protecting sensitive variables.

A public GraphQL endpoint should use persisted or allow-listed queries where practical. Complexity limits must be tested against legitimate queries; a limit that is too low damages availability, while one that is too high does not meaningfully constrain abuse.

4. WebSocket Security

WebSockets provide long-lived, bidirectional communication. The initial HTTP upgrade is only the beginning of the security lifecycle.

Authenticate the connection using a carefully designed mechanism and authorise each message or channel subscription. Do not assume that an authenticated socket may access every topic. Validate message type, size, encoding, sequence, and state transitions. Reject malformed frames and close connections that violate policy.

Controls should include idle and maximum connection lifetimes, per-identity and per-IP connection limits, message-rate limits, back-pressure, heartbeat handling, origin validation where relevant, and protection against cross-site WebSocket hijacking. Sensitive tokens should not be placed in URLs because URLs may be logged. On logout, privilege change, token revocation, or account suspension, servers should be able to terminate relevant connections.

5. Microservice and Service-to-Service Security

Microservices expand the number of trust boundaries. A gateway cannot replace authorisation inside services, because internal endpoints may be reached through queues, service meshes, operational tools, or a compromised peer.

Each service should authenticate its caller, validate the audience and issuer of credentials, enforce least-privilege service identities, and authorise the requested operation. Mutual TLS can authenticate workloads and encrypt traffic, but it does not by itself express business permissions. Short-lived workload credentials, secure secret management, network segmentation, and explicit service policies are preferable to shared static credentials.

Distributed systems also require propagation of security context. A trace identifier helps diagnosis but must not be confused with an identity assertion. Services should distinguish user identity, calling service identity, delegated authority, and original request context. Message brokers require equivalent controls: authenticated producers and consumers, topic-level permissions, schema validation, replay protection where needed, and retention policies.

Failure handling matters. Timeouts, circuit breakers, bounded retries, and idempotency keys reduce cascading failure and duplicate transactions. Retries must not become an amplification mechanism. Sensitive operations should use transaction-level authorisation and auditable state transitions.

6. Tokens, Sessions, and Token Abuse

Common token forms include opaque session identifiers and signed tokens such as JSON Web Tokens. A signed token provides integrity only if the signature is correctly verified; it does not automatically provide confidentiality. Sensitive claims should not be placed in a token unless their disclosure is acceptable or encryption is used.

A verifier should check signature algorithm policy, issuer, audience, expiry, not-before time where used, token type, and required scopes. It must reject algorithm confusion, malformed tokens, unexpected key identifiers, and tokens issued for another service. Key rotation requires overlapping validation keys, controlled publication, and a revocation or risk-response strategy.

Short expiry reduces exposure but can impair usability. Refresh tokens should be protected more strongly than access tokens, rotated on use where appropriate, bound to a client or device where feasible, and revoked after suspected theft. A token stored in a browser-accessible location is exposed to script compromise; an HttpOnly, Secure, appropriately SameSite cookie can reduce some risks, but cross-site request forgery and application architecture must still be addressed.

Token abuse includes replay, credential stuffing, automated enumeration, token theft, excessive scope, and use from anomalous devices or locations. Detection should consider impossible travel cautiously, sudden scope changes, unusual request sequences, failed verification, and high-value actions. Risk signals should support proportionate responses rather than indiscriminate blocking.

7. Excessive Data Exposure and Schema Validation

Returning a complete database record and relying on the client to hide fields is unsafe. APIs should deliberately define response contracts, classify fields, and return the minimum necessary data. Sensitive data includes credentials, recovery information, payment details, internal identifiers, precise location, and personal information.

Input validation has several layers:

  1. Parsing validation: Is the request valid JSON, correctly encoded, and within size limits?
  2. Schema validation: Are fields present, typed, bounded, and structurally valid?
  3. Semantic validation: Is the value meaningful, such as a permitted currency or date range?
  4. Authorisation validation: May this caller set or use the value?
  5. Business validation: Does the requested state transition comply with policy?

Validation should occur server-side even when generated clients or mobile interfaces perform local validation. Use strict schemas, reject unknown fields for security-sensitive operations, constrain strings and arrays, prevent unsafe deserialisation, and normalise data before comparison. Output encoding remains necessary when API data is inserted into HTML, SQL, logs, or commands by downstream systems.

8. Rate Limiting and Automated Abuse

Rate limiting protects availability and constrains brute force, scraping, enumeration, and economic abuse. A single global limit is rarely adequate. Policies may be applied per account, token, IP range, device, endpoint, operation, and organisation, with stricter thresholds for login, password reset, verification codes, search, and expensive queries.

A token-bucket model permits controlled bursts. If a bucket has capacity C tokens and refills at rate r tokens per second, a request consuming q tokens is permitted when at least q tokens are available. The bucket state is capped at C; this prevents unlimited accumulation during idle periods. The model must be implemented atomically across distributed nodes.

Rate limits should produce consistent responses, such as HTTP 429, with carefully designed retry guidance. Limits alone do not stop low-and-slow attacks, distributed automation, or valid-account abuse. Combine them with progressive friction, anomaly detection, proof-of-work or challenge mechanisms where justified, device and reputation signals, queueing, and business-level controls such as transaction limits.

Automation must be governed ethically. Security teams should distinguish authorised testing from abuse, minimise collection of behavioural data, document retention, and provide accessible alternatives when challenges affect legitimate users. AI-based anomaly detection can identify unusual sequences, but it may produce biased false positives and should remain explainable, monitored, and subject to human oversight for consequential actions.

9. Mobile and Rich-Client Security

A mobile or rich client is a potentially hostile environment. Code, strings, traffic behaviour, and locally cached data can be inspected or modified. Obfuscation and jailbreak/root detection may raise attacker cost but cannot replace server-side controls.

Do not embed long-lived privileged secrets, administrative keys, or universal API credentials in an application. Use platform-protected storage, such as Android Keystore or Apple Keychain, for tokens and cryptographic keys. Store the minimum data required, encrypt sensitive local databases, avoid sensitive data in logs, screenshots, backups, notifications, and analytics, and securely clear data on logout or device removal.

Certificate validation must verify the certificate chain, hostname, validity, and trusted roots using the platform’s secure networking stack. Disabling validation or accepting any certificate is not a security control. Certificate pinning can reduce exposure to compromised certificate authorities but creates operational risks during certificate rotation, incident response, and key loss. If used, maintain a safe rotation and recovery plan; never implement pinning in a way that prevents emergency updates.

For OAuth-based mobile login, use an external user-agent and the authorisation-code flow with Proof Key for Code Exchange (PKCE), rather than embedding a client secret that cannot remain confidential. Redirect URIs must be exact and protected against interception. Deep links require careful ownership and validation. Rich clients should use a strong Content Security Policy, avoid unsafe dynamic code, protect browser storage, and isolate privileged operations from untrusted content.

10. Testing, Observability, and Governance

An API security programme should begin with an inventory of endpoints, schemas, owners, data classifications, identities, and dependencies. Security tests should include:

  • Object and function authorisation tests using multiple users and roles.
  • Token validation, expiry, audience, replay, and revocation tests.
  • Schema fuzzing, boundary tests, malformed input, and mass-assignment tests.
  • GraphQL depth, alias, batching, and resolver-cost tests.
  • WebSocket message, subscription, reconnection, and termination tests.
  • Rate-limit, quota, and distributed-counter tests.
  • Mobile storage, backup, certificate, deep-link, and tamper-resistance tests.
  • Dependency, infrastructure, secret-scanning, and API configuration reviews.

Logs should record timestamp, request or trace identifier, service, authenticated subject or service, endpoint, decision, status, latency, and relevant risk signal. Avoid passwords, access tokens, full payment details, and unnecessary personal data. Metrics should reveal both security and reliability: authorisation denials, invalid tokens, 429 responses, schema failures, query complexity, connection counts, and high-value transaction anomalies.

Governance should assign data owners, define retention and deletion, manage third-party APIs, review scopes periodically, document threat models, and require security review for new endpoints and schema changes. Compliance obligations may arise from privacy, payment, health, critical-infrastructure, and breach-notification laws. Legal requirements vary by jurisdiction; technical controls should therefore be mapped to the organisation’s applicable obligations rather than assumed from a generic checklist.

Applied Case: Illustrative Mobile Banking API

Background

A fictional bank provides a mobile application backed by REST, GraphQL reporting, WebSocket payment notifications, and microservices for accounts and transfers.

Problem

A penetration test shows that a logged-in customer can change an account identifier in GET /accounts/{id} and view another customer’s balance. The transfer API returns internal risk fields, refresh tokens remain valid after password change, and automated scripts submit unlimited verification-code requests.

Analysis

The account issue is broken object-level authorisation. Excessive response serialisation exposes risk information. Token lifecycle design lacks effective revocation or risk invalidation. Unlimited verification requests create both availability and fraud risk. The weaknesses are related: identity is established, but object policy, data minimisation, lifecycle control, and abuse resistance are incomplete.

Approach and solution

The bank introduces repository queries constrained by authenticated subject and account relationship. It creates explicit response models containing only permitted fields and adds field-level policy to GraphQL resolvers. Refresh tokens are rotated, associated with a device record, and invalidated on password change and risk events. Verification requests receive per-account, device, IP, and operation limits, with progressive delay and monitoring.

The bank also implements strict transfer schemas, idempotency keys, step-up authentication for high-risk transfers, WebSocket subscription authorisation, and service-to-service identities. Security tests use two customer accounts, revoked tokens, malformed schemas, concurrent requests, and mobile backup inspection.

Outcome

The corrected design prevents cross-account access, reduces sensitive data exposure, limits automated code abuse, and improves incident investigation through structured logs. The bank accepts that no single control is sufficient: gateway controls, service policy, data modelling, token lifecycle, client protection, and monitoring must operate together.

Learning points

  1. A valid token does not prove access to a requested object.
  2. Response contracts are security boundaries.
  3. Token revocation and abuse controls must reflect business risk.
  4. Mobile clients cannot be treated as trusted enforcement points.
  5. Security tests should model multiple identities and realistic automation.

Challenges and Limitations

API security controls can conflict with usability, performance, availability, and accessibility. Fine-grained policy increases implementation and testing complexity. Rate limits may block shared networks or users with disabilities if poorly designed. Certificate pinning can cause outages. Distributed authorisation and revocation introduce consistency questions. GraphQL complexity estimates are imperfect, and anomaly detection can encode organisational bias. Security architecture must therefore use measurable risk analysis, staged deployment, clear exception processes, and continuous review rather than absolute assumptions.

Contemporary Developments and Best Practices

Current practice is moving toward API inventories generated from traffic and specifications, software bills of materials, workload identity, continuous authorisation, confidential computing for selected workloads, and automated schema-drift detection. These technologies are useful only when ownership and policy are clear.

A practical baseline is:

  • Inventory and classify every API and client.
  • Enforce TLS and secure certificate validation.
  • Authenticate and authorise every request, object, field, and message as appropriate.
  • Minimise data and use explicit request and response schemas.
  • Validate tokens, scopes, audience, issuer, expiry, and lifecycle.
  • Apply layered rate limits, quotas, and abuse detection.
  • Protect mobile storage and never trust client-side enforcement.
  • Test with multiple identities, malformed inputs, automation, and revoked credentials.
  • Monitor security decisions without logging secrets.
  • Review permissions, dependencies, schemas, and third-party integrations continuously.

Chapter Summary

API, mobile, and rich-client security is a system property spanning identity, authorisation, data modelling, transport, validation, availability, client protection, and monitoring. REST APIs require object- and function-level authorisation rather than authentication alone. GraphQL demands field-level policy and query-cost controls, while WebSockets require message and subscription authorisation throughout long-lived connections. Microservices need workload identity and local policy enforcement.

Tokens must be correctly validated, scoped, rotated, and revoked. Excessive data exposure is reduced through explicit response models and data minimisation. Strict schemas, semantic checks, rate limits, quotas, and abuse monitoring resist automated attacks. Mobile and rich clients should be treated as untrusted, using protected storage and correct certificate validation. Testing must reflect realistic users, roles, devices, automation, and distributed failure. Effective governance joins these technical measures to ownership, privacy, compliance, and continuous risk assessment.

Key Terms

API: An interface through which software requests data or operations.

Object-level authorisation: Checking whether a caller may access a specific resource instance.

Function-level authorisation: Checking whether a caller may perform a particular operation.

REST: An architectural style using resources and HTTP operations.

GraphQL: A typed API query language and execution system.

WebSocket: A protocol supporting persistent, bidirectional communication.

Microservice: A relatively small independently deployable service.

Scope: A permission associated with an access token.

Claim: A statement about an identity or token context.

Refresh token: A credential used to obtain a new access token.

Schema validation: Checking data structure, types, and constraints.

Mass assignment: Unintended modification of protected fields through automatic binding.

Rate limiting: Restricting request frequency or volume.

Token bucket: A rate-limiting model using a replenishing allowance of tokens.

Excessive data exposure: Returning more information than the client or user requires.

PKCE: A protocol extension protecting authorisation-code exchanges from interception.

Certificate pinning: Restricting acceptable certificates or public keys for a service.

Idempotency key: A client-supplied value used to prevent duplicate processing.

Zero trust: A model that continuously verifies requests rather than trusting network location.

Review Questions

Short Answer Questions

  1. Why is authentication insufficient to protect an API object?
  2. State two security controls specific to GraphQL.
  3. What is the purpose of PKCE in a mobile authorisation flow?
  4. Give two examples of sensitive data that should not normally be logged.
  5. Why should mobile clients not contain universal privileged API keys?

Long Answer Questions

  1. Explain how a REST API should prevent broken object-level authorisation, using an illustrative endpoint.
  2. Compare security concerns in REST, GraphQL, and WebSocket APIs.
  3. Discuss token validation, refresh-token protection, rotation, and revocation.
  4. Explain how a microservice architecture changes authentication and authorisation requirements.
  5. Design a layered rate-limiting and automated-abuse strategy for a verification-code API.

Analytical / Application Questions

  1. A customer can view another customer’s invoice by changing an identifier, although both users have valid tokens. Analyse the failure and propose code, policy, and testing controls.
  2. A GraphQL report causes high database load through nested aliases and repeated fields. Develop a mitigation plan that preserves legitimate reporting.
  3. A mobile application disables certificate validation because pinning caused an outage. Evaluate the security and operational consequences and recommend a safer recovery design.

Multiple Choice Questions with Answers

Question 1

Which control directly prevents a user from retrieving another user’s order by changing an order identifier?

A. Checking object ownership against the authenticated subject

B. Increasing password complexity

C. Disabling API documentation

D. Adding a response cache

Correct Answer: A. Checking object ownership against the authenticated subject

Question 2

Which GraphQL control most directly limits resource exhaustion from deeply nested queries?

A. Changing JSON to XML

B. Enforcing maximum query depth and complexity

C. Using longer passwords

D. Disabling TLS

Correct Answer: B. Enforcing maximum query depth and complexity

Question 3

What does a valid digital signature on a token primarily provide?

A. Guaranteed confidentiality of all claims

B. Integrity and authenticity when verification is correct

C. Automatic authorisation to every endpoint

D. Protection from token theft

Correct Answer: B. Integrity and authenticity when verification is correct

Question 4

Which practice is safest for a mobile application’s long-lived sensitive key material?

A. Store it in source code obfuscated with Base64

B. Store it in platform-protected key storage

C. Place it in a public configuration file

D. Send it in every URL

Correct Answer: B. Store it in platform-protected key storage

Question 5

What is the principal security purpose of an explicit response model?

A. To return every database column consistently

B. To minimise and control fields exposed to clients

C. To disable authorisation checks

D. To increase token lifetime

Correct Answer: B. To minimise and control fields exposed to clients

Question 6

A token bucket with capacity 10 currently contains 3 tokens. A request costs 4 tokens. Assuming no refill occurs, what is the result?

A. The request is allowed and 1 token remains

B. The request is allowed and 7 tokens remain

C. The request is rejected because fewer than 4 tokens are available

D. The bucket automatically expands to 14 tokens

Correct Answer: C. The request is rejected because fewer than 4 tokens are available

Question 7

Which statement about WebSocket security is most accurate?

A. Authentication during upgrade authorises every future message

B. Each sensitive message or subscription may require authorisation

C. WebSockets cannot be rate-limited

D. TLS removes the need for input validation

Correct Answer: B. Each sensitive message or subscription may require authorisation

Question 8

What is mass assignment?

A. Sending requests from many geographic locations

B. Unintended binding of client-supplied fields to protected object properties

C. Encrypting a database with multiple keys

D. Replicating a service across regions

Correct Answer: B. Unintended binding of client-supplied fields to protected object properties

Question 9

Which OAuth approach is recommended for public mobile clients?

A. Embedding a permanent client secret in the application

B. Authorisation code flow with PKCE

C. Sending passwords to every API endpoint

D. Using an unvalidated custom redirect URL

Correct Answer: B. Authorisation code flow with PKCE

Question 10

Which measure best supports secure microservice communication?

A. Trusting all traffic inside the private network

B. Using workload identities and enforcing policy within each service

C. Sharing one static administrator credential

D. Removing audit logs to improve performance

Correct Answer: B. Using workload identities and enforcing policy within each service

Web & Application Security
Chapter 6 of 14