RESTful API Development

Chapter 9
API Security, Privacy and Ethics

Bachelors Program in Full Stack Development
RESTful API Development   •   Bachelor

API Security, Privacy and Ethics

Introduction

RESTful APIs expose data and business capabilities to browsers, mobile applications, partners, and internal services. Their accessibility also makes them attractive targets for credential theft, authorization errors, abuse, privacy violations, and automated attacks. API security is therefore not merely a matter of adding a login screen. It is the coordinated protection of identity, permissions, data, availability, accountability, and human rights throughout the API lifecycle.

This chapter examines authentication and authorization using sessions, API keys, OAuth 2.0, OpenID Connect, and JSON Web Tokens (JWTs). It then connects these mechanisms to the OWASP API Security Top 10, privacy engineering, consent, auditability, and ethical data use.

Learning Objectives

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

  • distinguish authentication, authorization, accounting, and auditing;
  • select an appropriate session, API-key, OAuth 2.0, OIDC, or JWT design;
  • implement least privilege, secure token handling, and object-level authorization;
  • identify and mitigate major OWASP API risks;
  • design privacy-aware APIs based on purpose limitation, minimization, and consent;
  • evaluate security controls and ethical consequences in a realistic API system.

1. The Security Model of an API

Authentication answers “Who or what is making this request?” Authorization answers “What is that identity allowed to do?” Accounting records usage, while auditing evaluates records and controls. These functions are related but not interchangeable: a successfully authenticated user may still be forbidden to access a particular invoice.

A useful security objective is the CIA triad:

  • Confidentiality: only authorized parties can see information.
  • Integrity: data and operations cannot be changed improperly.
  • Availability: legitimate users can obtain service when needed.

API security also requires authenticity, accountability, privacy, and resilience. Transport Layer Security (TLS) should protect every production API connection, normally through HTTPS. TLS protects data in transit, but it does not decide whether a caller should access a record; application authorization remains necessary.

Threat modeling

A practical threat model identifies assets, actors, trust boundaries, entry points, abuse cases, and controls. Assets may include passwords, payment details, health information, personal identifiers, administrative functions, and service availability. Threats include credential stuffing, token theft, enumeration, injection, replay, denial of service, insider misuse, and accidental disclosure through logs.

Security should be designed using defense in depth. For example, an API may use TLS, short-lived access tokens, object-level authorization, input validation, rate limits, anomaly detection, encrypted storage, and an auditable incident-response process. No single control is sufficient.

2. Authentication and Authorization Mechanisms

Server-side sessions

With a session design, the client receives an unpredictable session identifier after login. The server stores the authenticated session and associated privileges. A browser normally carries the identifier in a cookie with Secure, HttpOnly, and an appropriate SameSite attribute.

Sessions are convenient for browser applications because the server can revoke them immediately. Important controls include session expiration, rotation after login or privilege change, logout invalidation, protection against session fixation, and CSRF defenses when cookies are automatically sent by a browser. Session identifiers must never appear in URLs or ordinary logs.

API keys

An API key identifies an application, project, or integration rather than necessarily a human user. Keys are useful for server-to-server access, public-but-rate-limited services, and development tools. They are not a complete substitute for user authentication because a copied key may not identify the individual using it.

Keys should be generated with a cryptographically secure random generator, scoped to the minimum required resources, stored as secrets, rotated, revocable, and transmitted over HTTPS. A key should not be embedded in a mobile application or browser bundle when it grants privileged access. Quotas and monitoring help limit damage after disclosure.

OAuth 2.0

OAuth 2.0 is an authorization framework that allows a resource owner to delegate limited access to a client through an authorization server. Its principal roles are resource owner, client, authorization server, and resource server. An access token is presented to the resource server, commonly using the Authorization: Bearer header.

For web and mobile applications, the Authorization Code flow with Proof Key for Code Exchange (PKCE) is the preferred modern pattern. The client creates a high-entropy verifier and a derived challenge, sends the challenge during authorization, and later proves possession of the verifier when exchanging the authorization code. This reduces the value of an intercepted code.

The state parameter helps defend browser authorization responses against request forgery. Redirect URIs must be exact and registered; wildcard redirects are dangerous. Client secrets cannot be treated as confidential in public clients such as mobile applications. Access tokens should be short-lived and narrowly scoped. Refresh tokens need stronger protection, rotation, and revocation policies.

OAuth scopes express delegated permissions, such as orders:read or orders:write. A scope is not a replacement for resource-level authorization: a caller with orders:read may still be allowed to see only orders belonging to that caller’s organization.

OpenID Connect

OpenID Connect (OIDC) adds an identity layer to OAuth 2.0. It introduces an ID token, usually a JWT, containing claims about the authenticated user and the issuer. A client must validate the token’s signature, issuer, audience, expiration, nonce, and other protocol requirements. OIDC enables single sign-on, but it does not automatically authorize every API operation. The API must still enforce its own policies.

JSON Web Tokens

A JWT is a compact, digitally signed or encrypted representation of claims. A signed JWT commonly has a header, payload, and signature. Typical claims include iss (issuer), sub (subject), aud (audience), exp (expiration), iat (issued-at time), and scope or roles.

A JWT is not encrypted merely because it is encoded. Anyone holding a typical signed JWT can decode its payload, so sensitive information should not be placed in it. Resource servers must use an explicit allow-list of algorithms, validate issuer and audience, check time claims, and reject expired or malformed tokens. They must not trust a role or user identifier without verifying the token’s signature and provenance.

JWTs are useful for distributed validation, but revocation is more difficult than with server-side sessions. Short lifetimes, refresh-token rotation, token introspection, deny lists for high-risk events, and key rotation can reduce this limitation. Clock-skew tolerance should be small and deliberately configured.

Comparison

MechanismStrong use caseMain risk or limitation
Session cookieBrowser applicationsCSRF and session theft
API keyService integration or quota identificationEasy to copy; weak user attribution
OAuth 2.0Delegated accessIncorrect redirect, scope, or token handling
OIDCFederated user authenticationInvalid claim validation or confused identity
JWTDistributed service authorizationLeakage, long lifetime, and difficult revocation

3. Authorization and Least Privilege

Authorization should be checked on every sensitive operation, at the point where the resource is accessed. Common models include:

  • RBAC: permissions are assigned to roles such as clerk or administrator.
  • ABAC: decisions use attributes of the subject, resource, action, and context.
  • ReBAC: relationships, such as “member of project,” determine access.

Least privilege means granting only the permissions necessary for a defined task, for the shortest reasonable time, to the smallest relevant audience. A robust decision considers the principal, action, resource, tenant, ownership, environmental context, and policy outcome. For example, GET /users/42/invoices/7 must verify that invoice 7 belongs to an organization the caller may access; checking only that the caller is logged in is inadequate.

Deny-by-default is safer than permitting access unless a special rule blocks it. Administrative endpoints should require stronger authentication, separate privileges, and additional monitoring. Multi-tenant APIs must enforce tenant isolation in queries, caches, background jobs, exports, and object storage—not only in the URL.

4. OWASP API Risks and Mitigations

The OWASP API Security Top 10 highlights recurring failure patterns:

  1. Broken Object-Level Authorization: users manipulate identifiers to access another user’s object. Enforce ownership or relationship checks server-side.
  2. Broken Authentication: weak passwords, unsafe recovery, or unvalidated tokens permit account compromise. Use established identity protocols, MFA where appropriate, secure recovery, and token validation.
  3. Broken Object-Property-Level Authorization: responses expose or accept fields a caller should not read or change. Use explicit response schemas and field-level write rules.
  4. Unrestricted Resource Consumption: expensive queries, large uploads, or repeated requests exhaust resources. Apply quotas, pagination limits, timeouts, payload limits, and cost-aware rate controls.
  5. Broken Function-Level Authorization: ordinary users invoke administrative functions. Centralize policy checks and test every role against every sensitive endpoint.
  6. Unrestricted Access to Sensitive Business Flows: automation abuses purchasing, voting, password reset, or ticket creation. Use workflow controls, velocity detection, risk signals, and human review where justified.
  7. Server-Side Request Forgery: an API fetches attacker-controlled URLs. Use allow-lists, network egress controls, safe URL parsing, and metadata-service protections.
  8. Security Misconfiguration: debug errors, permissive CORS, default credentials, or excessive documentation reveal or enable attacks. Harden environments and review configuration.
  9. Improper Inventory Management: undocumented, obsolete, or shadow APIs remain exposed. Maintain an inventory of versions, owners, data classes, and retirement dates.
  10. Unsafe Consumption of APIs: a service trusts third-party API data or availability without validation. Authenticate dependencies, validate schemas, set timeouts, and isolate failures.

Input validation should be based on expected types, lengths, formats, and business rules. Parameterized database operations prevent injection, but output encoding and authorization are still required. Error messages should help legitimate clients without revealing stack traces, secrets, or whether sensitive accounts exist.

5. Privacy, Consent, and Ethical Data Use

Security protects data from unauthorized access; privacy governs appropriate collection, use, sharing, retention, and deletion. Privacy principles commonly include purpose limitation, data minimization, accuracy, storage limitation, transparency, confidentiality, and accountability. Legal obligations vary by jurisdiction, so developers must involve qualified legal and privacy professionals rather than assuming that one global rule applies.

A privacy-aware API should:

  • document the purpose and lawful basis for each category of data;
  • collect only fields necessary for that purpose;
  • distinguish required consent from optional preferences;
  • make consent specific, informed, freely given, and withdrawable where consent is the basis;
  • avoid bundling unrelated purposes into one choice;
  • provide access, correction, deletion, portability, and objection processes where applicable;
  • define retention schedules and securely dispose of data;
  • restrict analytics and secondary use to compatible, disclosed purposes.

Consent is not a universal solution. It may be invalid where users lack a genuine choice or where a power imbalance exists. A service should not make essential access conditional on unrelated tracking without careful justification. Privacy notices should be understandable, timely, and consistent with actual API behavior.

Privacy by design includes pseudonymization, aggregation, encryption, access separation, selective disclosure, and minimizing data in tokens and logs. Pseudonymized data can often still be personal data if re-identification is reasonably possible. Production logs should avoid passwords, access tokens, full payment numbers, and unnecessary personal details. Audit records must balance accountability with data minimization.

Ethical data use asks not only “Can we collect this?” but also “Should we?” Relevant questions include whether the use creates unfair exclusion, whether individuals would reasonably expect it, whether automated decisions can be challenged, and whether benefits and risks are distributed fairly. AI systems consuming APIs require additional attention to data provenance, bias, explainability, human oversight, and prompt or training-data leakage.

6. Auditability, Monitoring, and Incident Response

An audit trail should record the actor, action, resource, time, result, source context, and correlation identifier, while avoiding unnecessary sensitive content. Logs should be tamper-resistant, access-controlled, time-synchronized, retained according to policy, and monitored for suspicious patterns. A log is evidence, not proof of ethical behavior; organizations must also define responsible review and escalation.

Security monitoring can detect repeated failures, impossible travel, unusual export volume, token reuse, privilege changes, and access outside normal patterns. Automated blocking should be proportionate and should include recovery paths to reduce harm from false positives.

A mature incident process includes preparation, detection, containment, eradication, recovery, notification where required, and lessons learned. Key rotation, session invalidation, token revocation, feature disablement, and communication plans should be tested before an incident occurs.

7. Applied Case: Illustrative University Research API

Background

A university exposes an API for a research portal. Students upload survey responses, researchers run approved analyses, and administrators manage projects. The initial system uses one shared API key and returns complete participant records.

Problem

A leaked key permits downloading all projects. Object identifiers are sequential, logs contain email addresses, and the API has no documented retention period. Researchers can access data from projects for which they have no approval.

Analysis

The design has weak authentication attribution, broken object-level authorization, excessive data exposure, poor inventory and auditability, and privacy risks. Consent obtained from participants covered a particular study, not unrestricted secondary research.

Approach

The university registers applications with an OAuth 2.0 authorization server and uses Authorization Code with PKCE for the web portal. Access tokens are short-lived and carry project-specific scopes. The API verifies issuer, audience, signature, expiration, and scopes, then performs a server-side relationship check between researcher, project, and approved protocol. Response schemas exclude direct identifiers unless a specific approved purpose requires them. Data is encrypted in transit and at rest; logs store pseudonymous subject identifiers and correlation IDs rather than raw responses. Rate limits, pagination, export review, key rotation, retention schedules, and an incident procedure are introduced.

Outcome

A stolen token has a narrower blast radius, unauthorized project access is denied, and audit records can connect actions to approved users and purposes. The design still requires governance: approval status can change, participants may withdraw where applicable, and researchers must not infer that technical access implies ethical permission.

Learning points

Authentication, authorization, privacy, and ethics must be designed together. A technically valid request may remain impermissible because it exceeds purpose, consent, or institutional policy. Data minimization improves both privacy and security by reducing the value of stolen data.

8. Implementation and Professional Practice

A secure development lifecycle should include threat modeling, security requirements, dependency management, code review, automated tests, dynamic testing, secret scanning, and independent penetration testing. Authorization tests should cover every role, tenant, object ownership condition, HTTP method, and failure path. Contract tests should verify that undocumented fields do not appear in responses.

Teams should maintain an API catalogue containing owners, environments, versions, data classifications, authentication method, scopes, dependencies, and retirement dates. Security decisions should be documented as architecture records. Developers should use established libraries and identity providers rather than implementing cryptography or OAuth protocol logic from scratch.

Security controls have trade-offs. Stronger verification may increase friction; detailed logging may increase privacy risk; JWT validation may improve scalability while complicating revocation; aggressive rate limits may exclude legitimate users. Professional judgment requires measuring these effects, consulting affected stakeholders, and selecting proportionate controls.

Contemporary Developments and Limitations

Passkeys and phishing-resistant multi-factor authentication are reducing reliance on passwords. Zero-trust architectures treat every request as requiring explicit verification rather than trusting a network location. Fine-grained authorization and continuous risk assessment are increasingly important in microservice and multi-cloud systems. However, new technologies do not remove governance problems: a decentralized token system can still encode excessive authority, and an AI-powered monitoring system can create discriminatory false positives.

No control guarantees security. Providers may suffer supply-chain compromise, identity systems may be unavailable, and valid credentials may be abused by insiders. Resilience therefore requires layered controls, tested recovery, clear accountability, and continuous improvement.

Chapter Summary

API security combines authentication, authorization, accounting, auditing, confidentiality, integrity, availability, and privacy. Sessions suit many browser applications; API keys identify integrations but provide limited user attribution; OAuth 2.0 delegates authorization; OIDC adds federated identity; and JWTs carry verifiable claims but require strict validation and careful revocation design. Least privilege, deny-by-default policies, tenant isolation, explicit schemas, and resource-level checks address common OWASP API risks. Privacy requires purpose limitation, minimization, meaningful consent, retention control, transparency, and respect for data-subject rights. Ethical API development also examines fairness, power, expectations, and the consequences of automated decisions. Secure systems are continuously tested, monitored, audited, and improved.

Key Terms

Authentication: Verification of the identity of a user, application, or service.

Authorization: Determination of which actions or resources an authenticated principal may use.

API key: A credential commonly used to identify an application or integration.

Session: Server-managed state associated with a client after authentication.

OAuth 2.0: A framework for delegated authorization.

OpenID Connect: An identity layer built on OAuth 2.0.

JWT: A compact token format carrying signed or encrypted claims.

Claim: A statement about a subject, issuer, audience, or token context.

Scope: A named permission requested or granted by an authorization server.

PKCE: A protocol extension that binds an authorization code to a client-held verifier.

Least privilege: Granting only necessary permissions for the shortest suitable period.

RBAC: Authorization based on assigned roles.

ABAC: Authorization based on subject, resource, action, and contextual attributes.

CSRF: An attack causing a browser to send an unwanted authenticated request.

SSRF: An attack that makes a server request an attacker-selected destination.

Purpose limitation: Using collected data only for specified, compatible purposes.

Data minimization: Collecting and retaining no more personal data than necessary.

Audit trail: A protected record of relevant actions and events.

Pseudonymization: Replacing direct identifiers while retaining a controlled possibility of linkage.

Review Questions

Short Answer Questions

  1. Distinguish authentication from authorization.
  2. Why is an API key usually insufficient as a complete user-identity mechanism?
  3. What problem does PKCE address?
  4. Name three JWT claims that a resource server should validate.
  5. Explain the principle of data minimization.

Long Answer Questions

  1. Compare sessions, API keys, OAuth 2.0, OIDC, and JWTs, including suitable use cases and limitations.
  2. Explain how least privilege and deny-by-default authorization can be implemented in a multi-tenant API.
  3. Discuss five OWASP API risks and propose practical mitigations for each.
  4. Explain how consent, purpose limitation, retention, and auditability interact in a privacy-aware API.
  5. Design a secure lifecycle for access tokens, refresh tokens, key rotation, logging, and incident response.

Analytical / Application Questions

  1. An authenticated customer changes /orders/1842 to /orders/1843 and sees another customer’s order. Identify the vulnerability, explain why authentication did not prevent it, and propose a control and test case.
  2. A mobile application contains a privileged API key in its compiled code. Analyze the risks and redesign the integration.
  3. A university wants to reuse identifiable student data for an unrelated AI project. Evaluate the request using purpose limitation, consent, minimization, fairness, governance, and security principles.

Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes authentication from authorization?

A. Authentication verifies identity; authorization determines permitted actions.

B. Authentication encrypts data; authorization compresses data.

C. Authentication limits rate; authorization records timestamps.

D. Authentication creates backups; authorization restores them.

Correct Answer: A. Authentication verifies identity; authorization determines permitted actions.

Question 2

Which OAuth 2.0 flow is generally preferred for a public web or mobile client requiring an authorization code?

A. Implicit flow without state

B. Authorization Code with PKCE

C. Password grant with a shared password

D. Client credentials using a mobile-embedded secret

Correct Answer: B. Authorization Code with PKCE

Question 3

What is the principal purpose of the JWT audience claim?

A. To identify the intended recipient of the token

B. To encrypt the token payload

C. To specify the user’s password

D. To rotate the signing key automatically

Correct Answer: A. To identify the intended recipient of the token

Question 4

A user changes an object identifier and accesses another customer’s record. Which OWASP risk is most directly involved?

A. Server-side request forgery

B. Broken object-level authorization

C. Improper inventory management

D. Unrestricted resource consumption

Correct Answer: B. Broken object-level authorization

Question 5

Which practice best reflects least privilege?

A. Giving every employee administrator access

B. Granting a service only read access to the records it needs

C. Using one permanent token for all services

D. Allowing access whenever a request is authenticated

Correct Answer: B. Granting a service only read access to the records it needs

Question 6

What does OpenID Connect add to OAuth 2.0?

A. A standardized identity layer

B. A database encryption engine

C. A network firewall

D. A replacement for TLS

Correct Answer: A. A standardized identity layer

Question 7

Which item should generally not be placed in an ordinary signed JWT payload unless its disclosure is acceptable?

A. A non-sensitive token identifier

B. Highly sensitive personal information

C. An expiration timestamp

D. An issuer identifier

Correct Answer: B. Highly sensitive personal information

Question 8

Which privacy principle requires collecting only information necessary for a stated purpose?

A. Data minimization

B. Availability

C. Non-repudiation

D. Load balancing

Correct Answer: A. Data minimization

Question 9

Which control most directly reduces harm from a leaked API key?

A. Making the key longer but never rotating it

B. Scoping, monitoring, rotating, and revoking the key

C. Printing the key in API documentation

D. Using the key in a browser URL

Correct Answer: B. Scoping, monitoring, rotating, and revoking the key

Question 10

Why must a resource server perform authorization checks even after validating an OAuth access token?

A. A valid token automatically grants every possible action

B. Token validity does not prove that the caller may access the particular resource

C. Authorization is performed only by the browser

D. TLS removes the need for authorization

Correct Answer: B. Token validity does not prove that the caller may access the particular resource

RESTful API Development
Chapter 9 of 15