Chapter 1
Web and Application Security Foundations
Advance Diploma in Cybersecurity
Web & Application Security
•
Advance Diploma
Web and Application Security Foundations
Introduction and context
Web and application security is the discipline of protecting software, data, users, and supporting infrastructure from unauthorized access, misuse, alteration, disruption, and destruction. It includes technical controls, secure development practices, operational procedures, governance, and user protection. Although security tools are important, effective security begins with an accurate mental model of how a web application works and where trust is placed.
A modern application rarely consists of one program running on one server. A typical service may include a browser or mobile client, a domain name, a DNS resolver, content-delivery networks, web servers, application services, APIs, databases, identity providers, cloud services, queues, and monitoring systems. Each connection creates an opportunity for failure or attack. Security therefore requires analysis of the complete system rather than only the visible web page.
This chapter establishes the foundations needed for later study of vulnerabilities such as injection, cross-site scripting, broken authentication, access-control failures, insecure configuration, and supply-chain compromise.
Learning objectives
By the end of this chapter, a learner should be able to:
describe the principal components and request flow of a web application;
distinguish DNS, HTTP, HTTPS, browsers, servers, sessions, and APIs;
identify trust boundaries and attack surfaces;
apply the confidentiality, integrity, and availability model;
explain least privilege, defence in depth, zero trust, and secure-by-design principles;
analyse a simple application architecture and recommend foundational controls;
recognise professional, ethical, and governance responsibilities in application security.
1. The web as a distributed system
The Web is an application platform built on interconnected protocols. A user enters a uniform resource locator (URL), such as https://shop.example/products/42, into a browser. The browser must determine the destination address, establish a network connection, send an HTTP request, receive a response, and render the result. The response may refer to additional resources, causing many further requests.
A simplified request path is:
Simplified web application request path
Figure: Simplified web application request path
Figure: A simplified web application request path.
The browser is an untrusted execution environment from the server's perspective. A user may modify requests using developer tools or a proxy, so server-side controls must not rely on the interface being honest. Similarly, an internal service should not automatically be trusted merely because it is inside a corporate network.
2. DNS, browsers, servers, and protocols
DNS
The Domain Name System (DNS) translates human-readable names into network information, commonly IP addresses. A resolver may obtain an answer from its cache, an authoritative name server, or a chain of delegated servers. DNS improves usability and supports service distribution, but it is not, by itself, proof that a particular server is trustworthy. DNS security measures such as DNSSEC provide authenticity for signed DNS data, while encrypted transports such as DNS over HTTPS protect resolver communication from some forms of observation and manipulation. These mechanisms address different risks and should not be confused with HTTPS.
Security concerns include domain hijacking, malicious or stale records, cache poisoning, subdomain takeover, and accidental exposure of internal hostnames. Organisations should control domain registration, protect registrar accounts with strong authentication, review DNS records, remove unused aliases, and monitor certificate and subdomain changes.
Browsers
A browser parses HTML, applies CSS, executes JavaScript, stores cookies, enforces the same-origin policy, and presents security indicators. The same-origin policy restricts scripts from freely reading resources belonging to another origin. An origin is commonly defined by scheme, host, and port. Cross-Origin Resource Sharing (CORS) allows carefully controlled exceptions, but a permissive CORS policy can expose sensitive responses to hostile sites.
Browser security features include sandboxing, content security policy, mixed-content blocking, cookie attributes, and permission controls. They reduce risk but do not replace server-side authorization. A browser can be automated, outdated, compromised, or controlled by a malicious user.
Servers and application services
A web server handles network connections, TLS termination, static files, and routing. An application server or service implements business rules, identity processing, validation, and data access. In a small deployment these functions may share one host; in a larger deployment they are separated behind reverse proxies, load balancers, service meshes, or API gateways.
A useful distinction is between authentication and authorization. Authentication answers “Who or what is making this request?” Authorization answers “What is that identity allowed to do?” A successful login must never imply unrestricted access.
3. HTTP and HTTPS
HTTP is a request–response application protocol. A request normally contains a method, target, headers, and possibly a body. Common methods include GET for retrieval, POST for submitting or creating an operation, PUT for replacement, PATCH for partial modification, and DELETE for removal. A response contains a status code, headers, and possibly a body. Status-code classes include 2xx success, 3xx redirection, 4xx client or request errors, and 5xx server errors.
HTTP is stateless at the protocol level: each request is independent unless an application adds state mechanisms. State may be represented by cookies, bearer tokens, server-side session records, or client-provided parameters.
HTTPS is HTTP carried through Transport Layer Security (TLS). TLS provides encryption against network observation, integrity protection against undetected modification, and authentication of the server through certificates and a trusted certification system. HTTPS does not guarantee that the application is honest, free from vulnerabilities, or safe to use. It protects the connection, not the endpoint after data is decrypted.
Good practice includes redirecting HTTP to HTTPS, using current TLS configurations, renewing certificates, enabling HSTS where appropriate, protecting cookies, avoiding sensitive data in URLs, and validating certificate errors rather than teaching users to ignore them. TLS termination at a reverse proxy must be treated as a trust boundary: traffic from the proxy to an internal service may also require encryption and authentication, especially across hosts or networks.
4. Sessions, identity, and state
Because HTTP is stateless, applications require a method to associate multiple requests with a user or client. A traditional server-side session stores state on the server and gives the browser a random session identifier in a cookie. The identifier should be unpredictable, short-lived where practical, rotated after authentication or privilege change, and invalidated on logout or suspected compromise.
Important cookie attributes include:
Attribute
Security purpose
Secure
Sends the cookie only over HTTPS.
HttpOnly
Prevents ordinary JavaScript from reading the cookie. It does not stop all cross-site request forgery or session abuse.
SameSite
Restricts cross-site sending and can reduce cross-site request forgery risk.
Domain and Path
Limit where the browser sends the cookie; overly broad scope increases exposure.
Tokens such as JSON Web Tokens can carry claims and be validated without a central session lookup, but they introduce difficult revocation, key-management, audience-validation, and token-storage decisions. A token is not secure merely because it is encoded or signed. The application must validate signature, issuer, audience, expiry, algorithm expectations, and permissions according to its design.
Cross-site request forgery (CSRF) occurs when a victim's browser sends an authenticated request initiated by another site. Defences include appropriate SameSite settings, anti-CSRF tokens, origin checks, and designing state-changing operations carefully. Cross-site scripting (XSS), by contrast, involves unintended script execution in a user's browser and requires output encoding, input handling, content security policy, and safe coding practices.
5. APIs and service-to-service communication
An API is a defined interface through which software components exchange data or invoke operations. REST-style APIs commonly use HTTP resources and methods; GraphQL allows clients to request structured fields; event-driven systems may communicate through queues or topics. Regardless of style, an API is a security boundary and must define identity, authorization, validation, error behaviour, rate limits, and data exposure.
Common API weaknesses include object-level authorization failure, excessive data exposure, mass assignment, unrestricted resource consumption, weak token validation, insecure default endpoints, and verbose error messages. Every request should be authorized for the specific object and operation. For example, a user who may view their own invoice must not automatically be able to retrieve another customer's invoice by changing an identifier.
Service accounts should have narrowly scoped permissions, separate credentials, rotation procedures, and auditable use. Secrets must not be embedded in source code or exposed in logs. Mutual TLS, signed requests, workload identity, and short-lived credentials may be appropriate for high-value service-to-service communication.
6. Trust boundaries and attack surface
A trust boundary is a transition between areas with different assumptions about identity, integrity, or control. Examples include the browser-to-server boundary, the public network-to-perimeter boundary, a reverse proxy-to-application boundary, an application-to-database boundary, and a third-party integration boundary.
An attack surface is the collection of reachable entry points, components, interfaces, data flows, identities, and dependencies that could be targeted. It includes visible pages and APIs, administrative interfaces, file-upload functions, background jobs, cloud permissions, dependencies, DNS records, CI/CD systems, and support tools.
Threat modelling helps make these boundaries explicit. A practical process is:
define system scope and valuable assets;
draw data flows and identify trust boundaries;
enumerate threats, including abuse of legitimate functions;
estimate likelihood and impact;
select preventive, detective, and corrective controls;
validate controls through testing and review.
STRIDE is one useful classification: spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege. It is a prompt for analysis rather than a complete risk methodology. Threat models must be updated when architecture, dependencies, data, or business processes change.
7. The CIA triad and security objectives
The confidentiality, integrity, and availability model provides a compact way to classify security objectives.
Confidentiality means preventing unauthorized disclosure. Controls include access control, encryption, data minimisation, segregation, and careful logging.
Integrity means preserving accuracy, completeness, authenticity, and protection from unauthorized modification. Controls include authorization, input validation, digital signatures, change control, and tamper-evident audit records.
Availability means ensuring that authorized users can obtain services and data when needed. Controls include redundancy, capacity planning, backups, rate limits, resilience, and incident recovery.
The triad is not exhaustive. Authenticity, accountability, privacy, safety, and non-repudiation may be explicit requirements. Controls can also create trade-offs: extensive logging may improve accountability but create privacy and confidentiality risks; aggressive rate limiting may improve availability for the service while inconveniencing legitimate users.
Risk is best treated as a reasoned combination of threat, vulnerability, exposure, and consequence rather than as a precise natural constant. Quantitative scoring can support prioritisation, but numerical scores are dependent on assumptions and should not disguise uncertainty.
8. Foundational security principles
Least privilege
Least privilege gives an identity, process, or component only the permissions needed for its legitimate task, for only as long as necessary. A reporting service should not have database deletion rights; an application should not run as an operating-system administrator; a developer should not retain production access indefinitely. Least privilege requires role design, separation of duties, periodic review, and removal of unused permissions.
Defence in depth
Defence in depth uses multiple independent or partially independent controls. For example, secure coding, parameterized queries, restricted database permissions, network segmentation, monitoring, backups, and incident response together reduce the chance that one failure becomes a serious breach. Layers should not be assumed independent: a shared identity provider or common administrator account may create a common failure point.
Zero trust
Zero trust is an architectural approach in which no user, device, service, or network location is automatically trusted. Access is continuously evaluated using identity, device and workload context, resource sensitivity, policy, and observed risk. Zero trust does not mean “trust nothing and block everything”; it means make trust explicit, limited, verifiable, and subject to reassessment. Network location alone is not sufficient evidence of authorization.
Secure by design and secure by default
Secure by design incorporates security requirements during architecture and product design rather than treating security as a final test. Secure defaults provide the safer configuration without requiring expert intervention. Design questions include: What data is collected? Who can access it? What happens when an authorization service is unavailable? Can a user recover safely? Can an administrator audit decisions? Privacy by design applies similar reasoning to personal information through minimisation, purpose limitation, retention control, and transparency.
Other important principles include fail-safe failure, complete mediation, separation of duties, input validation, deny-by-default authorization, and simplicity. A control that cannot be understood, operated, or monitored may fail in practice even if its design is theoretically strong.
An illustrative regional clinic launches a portal where patients book appointments, view laboratory results, and exchange messages with clinicians. The portal uses a browser interface, a public API, an identity provider, an appointment service, a records database, cloud object storage, email notifications, and a third-party payment service.
Problem
A security review finds that the API accepts a patient identifier supplied by the client and checks only whether the user is logged in. The web interface hides records belonging to other patients, but the API does not enforce ownership. The application also logs full laboratory results and sends password-reset links that remain valid for several days.
Analysis
The browser-to-API boundary is untrusted: a user can alter identifiers and requests. The API-to-database boundary is another trust boundary because the application account can access sensitive health information. The attack surface includes the API, password recovery, logs, object storage, integrations, and administrative functions. Confidentiality risk is high because health information is exposed. Integrity risk exists if an attacker can alter appointments or messages. Availability matters because patients may need urgent information.
Approach and solution
The clinic should implement object-level authorization on every record request, using the authenticated subject and server-side policy rather than a hidden field or interface control. It should separate roles for patients, clinicians, support staff, and administrators; restrict database permissions; encrypt sensitive data; redact health information from logs; and apply retention limits.
Password-reset tokens should be random, single-use, short-lived, and invalidated after successful use or password change. Multi-factor authentication should be considered for clinicians and administrators. API schemas should validate types, lengths, and allowed fields. Rate limiting and monitoring should address enumeration and automated abuse. The payment integration should receive only the data it needs, with verified callback authenticity.
Outcome
After redesign, unauthorized record access is blocked at the API layer, sensitive logs are reduced, recovery is safer, and audit records identify the actor, action, target, and result without unnecessarily copying medical content. Testing includes authorization tests for horizontal and vertical privilege escalation, dependency review, configuration review, and incident exercises.
Learning points
The case demonstrates that a hidden user-interface control is not authorization, HTTPS does not correct an access-control defect, and privacy, security, availability, and clinical safety must be considered together. It also shows why trust boundaries and data flows should be documented before controls are selected.
10. Professional practice, governance, and contemporary developments
Application security operates within legal, contractual, and professional obligations. Personal data protection laws commonly require lawful processing, security safeguards, breach handling, minimisation, and retention controls, although exact duties depend on jurisdiction. Sector rules may impose additional requirements for health, finance, education, or critical infrastructure. Practitioners should obtain authorization before testing, protect collected evidence, avoid unnecessary personal-data access, and report weaknesses responsibly.
Secure development should integrate security requirements, code review, dependency management, secrets scanning, static and dynamic testing, infrastructure-as-code review, and controlled release processes. Automated tools are valuable but imperfect: a scanner may miss business-logic flaws and may report issues that require human assessment.
Artificial intelligence introduces both opportunities and risks. AI-assisted code generation can improve productivity but may reproduce vulnerable patterns, mishandle secrets, or create unreviewed dependencies. AI services may also receive confidential prompts or training data. Organisations should define approved uses, prohibit sensitive disclosure where appropriate, review generated code, test model-integrated applications, and address prompt injection, insecure tool use, and excessive agent permissions. AI is not a substitute for threat modelling or accountable human decisions.
Contemporary architectures increasingly use cloud services, containers, microservices, software-as-a-service dependencies, and continuous delivery. These environments make identity, configuration, software provenance, observability, and supply-chain risk central concerns. The fundamental principles remain applicable: establish trust explicitly, minimize privileges, protect data, validate every boundary, and design for recovery.
Best-practice checklist
Inventory applications, APIs, dependencies, data stores, and external services.
Classify data and identify legal, safety, and business requirements.
Model trust boundaries and abuse cases before implementation.
Use HTTPS correctly and protect certificates, keys, and session identifiers.
Enforce authorization server-side for every sensitive action and object.
Apply secure defaults, least privilege, separation of duties, and short-lived credentials.
Validate input and encode output according to context.
Keep secrets out of source code, logs, URLs, and client-side bundles.
Log security-relevant events without unnecessarily recording sensitive content.
Test failure modes, recovery, rate limits, and authorization—not only normal functionality.
Patch dependencies and verify software provenance.
Monitor, rehearse incident response, and update the threat model as the system changes.
Chapter Summary
Web applications are distributed systems composed of clients, DNS, network protocols, servers, application services, APIs, identity mechanisms, data stores, and third parties. HTTP provides request–response communication, while HTTPS adds TLS-based confidentiality, integrity, and server authentication; neither guarantees secure application logic. Browsers enforce useful controls but cannot be trusted to enforce server authorization.
Sessions connect otherwise stateless requests to identities, and their identifiers and tokens require careful lifecycle, scope, storage, and revocation controls. APIs are security boundaries that must validate requests and enforce authorization for each operation and object. Trust boundaries and attack surfaces provide a structured way to reason about where assumptions change and where attackers may act.
The CIA triad frames confidentiality, integrity, and availability, while authenticity, privacy, accountability, and safety may also be required. Least privilege, defence in depth, zero trust, secure-by-design, secure defaults, complete mediation, and separation of duties form a practical foundation for architecture and operations. Effective security is socio-technical: it combines design, implementation, governance, testing, monitoring, ethical conduct, and recovery.
Key Terms
Attack surface: The reachable components, interfaces, identities, data flows, and dependencies that may be targeted.
Authentication: Establishing the identity of a user, service, device, or process.
Authorization: Determining whether an authenticated subject may perform a particular action on a particular resource.
API: A defined software interface for exchanging data or invoking operations.
Availability: The property that authorized users can access services and data when required.
Confidentiality: Protection against unauthorized disclosure.
DNS: The distributed naming system that resolves domain names to network information.
Defence in depth: Use of multiple security layers so that one control failure does not determine the outcome.
HTTPS: HTTP protected by Transport Layer Security.
Integrity: Protection of data and processes against unauthorized or undetected alteration.
Least privilege: Granting only the permissions necessary for an authorized task.
Origin: A security identity generally defined by scheme, host, and port.
Session: State that associates related requests with a user or client.
TLS: A protocol providing protected communication and server authentication when correctly configured.
Threat model: A structured representation of assets, actors, threats, boundaries, and controls.
Trust boundary: A point where assumptions about identity, control, or integrity change.
Zero trust: An approach that requires explicit, contextual, and continually evaluated authorization rather than implicit network trust.
Review Questions
Short Answer Questions
What security services does TLS provide, and what does it not guarantee?
Why is a browser an untrusted client from the application's perspective?
Distinguish authentication from authorization.
What is a trust boundary? Give two examples.
State the three elements of the CIA triad.
Long Answer Questions
Explain the complete path of a browser request from URL entry to application response, identifying security concerns at each major component.
Compare server-side sessions with token-based sessions, including lifecycle and revocation considerations.
Explain how least privilege and defence in depth complement each other in a web application.
Discuss how zero trust changes assumptions about internal networks and service-to-service communication.
Describe a secure-by-design process for a new public API.
Analytical / Application Questions
An authenticated customer can change an invoice number in an API request and view another customer's invoice. Identify the trust-boundary failure, classify the principal CIA impact, and propose controls.
A company terminates TLS at a cloud load balancer and sends unencrypted traffic to an application server in another network segment. Analyse the risks and recommend an architecture.
Threat-model a file-upload feature for a university portal. Identify assets, entry points, at least four threats, and preventive, detective, and recovery controls.
Multiple Choice Questions with Answers
Question 1
Which statement best describes HTTPS?
A. It guarantees that the application contains no vulnerabilities.
B. It protects HTTP traffic using TLS and can provide confidentiality, integrity, and server authentication.
C. It replaces the need for authorization checks.
D. It prevents all attacks against a web server.
Correct Answer: B. It protects HTTP traffic using TLS and can provide confidentiality, integrity, and server authentication.
Question 2
What is the primary purpose of DNS?
A. To encrypt application data
B. To authenticate every web user
C. To translate domain names into network information such as IP addresses
D. To store browser sessions
Correct Answer: C. To translate domain names into network information such as IP addresses
Question 3
Which control most directly enforces object-level authorization?
A. Hiding an object identifier in the user interface
B. Checking on the server that the authenticated subject may access the requested object
C. Using a longer URL
D. Enabling browser caching
Correct Answer: B. Checking on the server that the authenticated subject may access the requested object
Question 4
Which cookie attribute helps prevent ordinary client-side JavaScript from reading a cookie?
A. Secure
B. SameSite
C. HttpOnly
D. Domain
Correct Answer: C. HttpOnly
Question 5
Which principle grants a process only the permissions required for its task?
A. Least privilege
B. Availability
C. Open trust
D. Maximum reachability
Correct Answer: A. Least privilege
Question 6
Which item is an example of a trust boundary?
A. A page heading within one HTML document
B. The transition between a public API and a protected database
C. A user changing browser font size
D. A cached image on the same page
Correct Answer: B. The transition between a public API and a protected database
Question 7
A system remains reachable, but unauthorized users can alter records. Which CIA property is most directly violated?
A. Confidentiality
B. Integrity
C. Availability
D. Portability
Correct Answer: B. Integrity
Question 8
What is a central idea of zero trust?
A. All internal network traffic is trusted automatically.
B. Only external users require authentication.
C. Authorization should be explicit, contextual, and continually evaluated.
D. Security is achieved solely through perimeter firewalls.
Correct Answer: C. Authorization should be explicit, contextual, and continually evaluated.
Question 9
Which practice is most appropriate for a password-reset token?
A. Make it predictable so support staff can reproduce it.
B. Store it permanently in a URL.
C. Make it random, short-lived, single-use, and invalidated after use.
D. Place the user's password inside it.
Correct Answer: C. Make it random, short-lived, single-use, and invalidated after use.
Question 10
Why is a hidden form field insufficient for authorization?
A. Users cannot submit forms containing hidden fields.
B. The browser can be modified and the field can be changed before submission.
C. Hidden fields are always encrypted.
D. Hidden fields are processed only by DNS.
Correct Answer: B. The browser can be modified and the field can be changed before submission.