Web Application Security and Secure Coding

Chapter 8
Browser and Front-End Security

Post Graduate Diploma in Full Stack Development
Web Application Security and Secure Coding   •   Post Graduate

8. Browser and Front-End Security

Introduction and Context

A modern web application is not secured solely by protecting its server, database, or network. The browser is an active execution environment in which application code, third-party scripts, user-controlled data, cookies, tokens, and browser APIs interact. This makes the front end both a usability platform and a significant security boundary.

Browser and front-end security concerns arise when an application allows data or code to cross trust boundaries without adequate controls. An attacker may inject executable script through a comment field, cause a victim’s browser to submit an unwanted request, embed an application inside a deceptive frame, extract sensitive data from browser storage, or compromise a third-party dependency used by thousands of pages. These attacks differ in mechanism, but they share a central problem: the browser is induced to perform an action under a level of trust that the application did not intend.

For full-stack developers, front-end security is therefore not limited to escaping HTML. It requires coordinated use of secure coding, browser security policies, cookie controls, origin rules, dependency governance, and sound architectural decisions. The server remains responsible for authoritative validation and authorization, but the client must also be designed so that hostile input and untrusted code have limited opportunity to cause harm.

Learning Objectives

After studying this chapter, the learner should be able to:

1. Explain the browser security model, origins, trust boundaries, and the same-origin policy.

2. Distinguish reflected, stored, and DOM-based cross-site scripting.

3. Select suitable output encoding, sanitization, and Content Security Policy controls.

4. Explain cross-site request forgery and implement layered defenses using tokens and cookie attributes.

5. Assess clickjacking risks and apply framing restrictions.

6. Compare cookies, web storage, and in-memory storage for different types of data.

7. Configure CORS without confusing cross-origin access with authentication or authorization.

8. Identify front-end supply-chain risks and establish practical dependency controls.

9. Apply a secure front-end review process to realistic application scenarios.

The Browser as a Security Boundary

The browser separates web applications primarily through the concept of an origin. An origin is defined by scheme, host, and port. For example, `https://app.example.com:443` and `http://app.example.com:80` have different origins, as do `https://app.example.com` and `https://api.example.com`. The same-origin policy restricts one origin from freely reading data belonging to another origin.

The same-origin policy is not an absolute prohibition on communication. Browsers permit selected cross-origin activities, such as loading images, stylesheets, and some scripts. They also support controlled mechanisms such as CORS, `postMessage`, and cross-origin resource sharing policies. The important distinction is between sending a request, loading a resource, and reading a response. A browser may allow a cross-origin request to be sent while preventing the initiating page from reading the response.

Security decisions must also account for trust boundaries within one application. A page may contain code from the application itself, an analytics provider, a customer-supplied template, and a marketing tag. All scripts executing in the page generally have powerful access to the page’s DOM and can often act with the user’s authority. Thus, adding a third-party script is not merely a functional decision; it is a delegation of trust.

Several browser concepts recur throughout this chapter:

  • Origin: The combination of scheme, host, and port used to identify a web security context.
  • Document Object Model (DOM): The browser’s object representation of a page, which scripts can read and modify.
  • Credentialed request: A request that includes credentials such as cookies, client certificates, or certain authentication information.
  • Browser security policy: A response-defined rule that limits actions such as framing, resource loading, or cross-origin access.
  • Trust boundary: A point at which data, code, or authority moves between parties with different levels of trust.

Cross-Site Scripting: Data Becoming Code

Cross-site scripting (XSS) occurs when an attacker causes a browser to execute unintended script in the security context of a trusted application. The impact may include reading page data, altering displayed content, performing actions as the victim, accessing non-HttpOnly tokens, or capturing user input. XSS is especially serious because the browser treats the injected code as if it came from the legitimate application origin.

Forms of XSS

Reflected XSS occurs when malicious input is included in a request and immediately reflected in the response. A vulnerable search page might place a query parameter directly into HTML. If the response contains the attacker’s input without appropriate encoding, a crafted link can execute script when a victim opens it.

Stored XSS occurs when malicious content is saved by the application and later displayed to other users. Common locations include discussion posts, profile fields, support tickets, and administrative dashboards. Stored XSS is often more damaging because the attacker needs to persuade the application or a privileged user to display the content only once.

DOM-based XSS occurs primarily in client-side code. The server may return a harmless document, but JavaScript reads attacker-controlled data from a URL fragment, query string, message, or storage and writes it into a dangerous DOM sink. For example, assigning untrusted data to `innerHTML` can create an injection point.

The distinction is useful for diagnosis, but the defense principle is broader: untrusted data must not be interpreted as executable code. The application should preserve the difference between data and code at every processing stage.

Context-Sensitive Output Encoding

Encoding must match the location in which data is inserted. HTML element content, HTML attributes, JavaScript strings, CSS values, and URLs have different parsing rules. Encoding a value for HTML text does not automatically make it safe inside a JavaScript string or URL.

The safest pattern is to place data into a context using APIs that treat it as data. In client-side code, `textContent` is generally safer than `innerHTML` when displaying text. For attributes, use property assignment or framework mechanisms that perform appropriate escaping. Avoid constructing scripts, event-handler attributes, CSS expressions, or executable URLs from user input.

A useful design rule is to avoid dangerous contexts rather than attempting to encode into them. If a user needs to select a color, accept a constrained value such as a known palette identifier instead of placing arbitrary input in a style declaration. If a user needs to provide a link, validate the URL scheme and destination policy rather than accepting arbitrary `javascript:` or unusual URL forms.

Sanitization is different from encoding. Encoding displays input as text, whereas sanitization removes or neutralizes disallowed markup while preserving an intentionally permitted subset. Rich-text editors may require sanitization because legitimate formatting is expected. A well-maintained, security-focused sanitizer should be used; ad hoc regular expressions are not reliable HTML parsers.

Content Security Policy

Content Security Policy (CSP) is a response policy that restricts where a browser may load scripts, styles, images, frames, and other resources. A policy can reduce the impact of XSS by preventing inline scripts, restricting script sources, and limiting powerful features. A typical policy may allow scripts only from the application’s own origin and approved nonces.

A nonce-based policy generates a fresh unpredictable value for each response and permits only script elements carrying that nonce. Hash-based policies authorize specific inline script content by cryptographic hash. Modern deployments should avoid broad allowances such as `unsafe-inline` and should treat `unsafe-eval` as a significant risk because it permits dynamic code evaluation.

CSP is a defense-in-depth measure, not a substitute for output encoding. A permissive policy, a policy misconfiguration, or a browser feature not covered by the policy may leave an injection exploitable. CSP should be developed using reporting or monitoring modes, reviewed for necessary sources, and enforced after legitimate application behavior is understood.

Cross-Site Request Forgery and the Meaning of User Intent

Cross-site request forgery (CSRF) occurs when an attacker causes a victim’s browser to send an authenticated request to a target application without the victim intentionally initiating that action. Cookies are automatically attached to matching requests, so a malicious page may cause a browser to submit a form or issue a request to another site. The target server may see a valid session cookie and incorrectly interpret the request as intentional.

CSRF is most relevant when authentication relies on automatically included credentials, especially cookies. It targets state-changing operations such as changing an email address, creating an order, transferring funds, or modifying account settings. A successful CSRF attack does not require the attacker to read the response; causing the action may be sufficient.

Defensive Controls

A synchronizer token stores a random token in the user’s session and requires the same token in a form field or request header. The server verifies the value before processing a state-changing operation. The token must be unpredictable, bound to the relevant session, and validated server-side.

A double-submit cookie places a random value in a cookie and requires the client to submit the same value in a request parameter or header. The server compares the two values. This approach must be implemented carefully, particularly where subdomains or cookie injection could affect trust.

The `SameSite` cookie attribute instructs the browser when to include cookies in cross-site contexts. `Strict` provides stronger isolation but may affect some legitimate navigation flows; `Lax` is commonly more compatible and provides meaningful protection for many requests; `None` permits cross-site use and requires `Secure`. SameSite should be regarded as an important layer rather than the only CSRF defense, especially for sensitive operations and complex authentication flows.

State-changing operations should use appropriate HTTP methods and should not be implemented as simple, side-effecting `GET` requests. Server-side authorization and business-rule checks remain necessary because a valid CSRF token proves request origin or session association, not that the user is authorized to perform every operation.

Clickjacking and Framing Controls

Clickjacking is an interface-redressing attack in which a victim is persuaded to click on an obscured or misleading interface element. An attacker may embed a legitimate application in an iframe and place deceptive content over it. The victim believes that a visible button performs one action while the click activates a sensitive control in the framed application.

The principal defenses are `Content-Security-Policy: frame-ancestors ...` and the older `X-Frame-Options` header. `frame-ancestors` provides flexible control over which origins may embed a page. `DENY` prevents all framing, while `SAMEORIGIN` permits framing only by the same origin when supported by the deployment requirements. Applications should also consider user-interface confirmation for high-impact actions and avoid relying solely on visual secrecy.

Frame protection should be tested across all sensitive pages, including authentication, administration, payment, and account-management screens. A policy applied only to the home page does not protect a vulnerable administrative endpoint.

Cookies, Web Storage, and Client-Side Secrets

Browser storage choices affect confidentiality, integrity, availability, and usability. Cookies can be automatically sent to a server and can be protected with attributes. `HttpOnly` prevents ordinary JavaScript from reading a cookie, reducing token theft through many XSS payloads. `Secure` limits transmission to HTTPS. `SameSite` controls cross-site transmission. Narrow `Domain` and `Path` settings reduce unnecessary exposure.

`localStorage` and `sessionStorage` are accessible to JavaScript. They are convenient for client-side preferences and some application data, but any successful script execution in the origin may read them. Storing long-lived bearer tokens in web storage therefore increases the consequences of XSS. In-memory storage reduces persistence and may lower the value of stolen data after a page reload, although it does not prevent access during an active compromise.

No browser storage mechanism should be treated as a trusted vault for secrets. A client-controlled value can be modified, deleted, or replayed. Sensitive authorization decisions must be enforced on the server. Applications should minimize token lifetime, rotate credentials where appropriate, avoid placing secrets in URLs, and never embed server credentials or private API keys in shipped front-end code.

CORS: Controlled Cross-Origin Access

Cross-Origin Resource Sharing (CORS) allows a server to state which other origins may read its responses through browser requests. It is a browser-enforced access-control mechanism, not a general replacement for authentication or authorization.

A secure CORS configuration identifies approved origins rather than reflecting arbitrary values from the request. If credentials are allowed, the server must use a specific permitted origin and cannot safely combine credentialed access with a wildcard origin. Preflight requests using the `OPTIONS` method may be sent before requests with non-simple methods or headers. The server must validate the requested method and headers and return only the permissions actually intended.

CORS does not prevent non-browser clients from sending requests. It also does not protect an API from a malicious authenticated client. Consequently, APIs still require authentication, authorization, input validation, rate limiting, and appropriate CSRF defenses where cookies are used.

Front-End Supply-Chain Security

A front-end application may depend on hundreds of direct and transitive packages, build plugins, hosted libraries, fonts, analytics services, and content-delivery networks. A compromised dependency can execute with the privileges of the application’s own code. The danger is amplified because production bundles may make it difficult to identify which package introduced a behavior.

Supply-chain controls include maintaining a dependency inventory, locking versions, reviewing changes, scanning for known vulnerabilities, removing unused packages, and monitoring package ownership and release behavior. Lockfiles improve reproducibility but do not by themselves prove that a package is trustworthy. Dependency updates should be tested and reviewed rather than accepted automatically without governance.

Subresource Integrity (SRI) allows a browser to verify that a fetched external resource matches an expected cryptographic hash. It is useful for pinned scripts and stylesheets delivered from approved external locations. SRI is less convenient for resources that change frequently and does not replace vendor assessment or CSP.

Third-party scripts should be minimized and isolated where practical. A tag-management system, advertising script, or analytics library can access page content and user interactions. Where a capability does not need DOM access, sandboxed iframes, carefully designed APIs, or server-side integration may reduce trust. Secret values must never be placed in client bundles, source maps published without consideration, or public configuration files merely because they are difficult for casual users to find.

A Secure Front-End Engineering Workflow

Security is strongest when integrated into the development lifecycle rather than added during a final review. A practical workflow begins with threat modeling: identify sensitive actions, trusted origins, data sources, third-party code, authentication mechanisms, and possible attacker-controlled inputs.

During implementation, teams should prefer framework auto-escaping, safe DOM APIs, centralized URL and HTML sanitization, secure cookie configuration, and explicit CORS policies. Code review should search for dangerous sinks such as `innerHTML`, dynamic script creation, `eval`, uncontrolled redirects, unvalidated message handlers, and broad storage of tokens.

Testing should combine automated and manual techniques. Static analysis can identify unsafe DOM patterns and dependency weaknesses. Dynamic testing can inspect response headers, attempt injection in multiple contexts, verify CSRF rejection, test framing behavior, and examine cross-origin requests. Browser developer tools are valuable for checking cookies, storage, CSP violations, network headers, and unexpected third-party resources.

Production monitoring should include CSP reports, dependency alerts, unusual authentication activity, and changes to external resources. Security headers must be verified in the deployed environment because reverse proxies, content delivery networks, and hosting platforms may alter or remove them.

Illustrative Case Study: Securing a Customer Support Portal

Background

A fictional company, HelpDesk Cloud, operates a customer support portal. Customers submit tickets, agents reply to them, and supervisors can export ticket data. The application uses a single-page front end, cookie-based authentication, a separate API origin, and several third-party analytics scripts.

Situation and Problem

A security review identifies three weaknesses. Ticket replies are rendered with `innerHTML`, allowing stored XSS. The API accepts cookie-authenticated state-changing requests without a CSRF token. Finally, the front end loads an external script from a broad, unpinned URL and allows the portal to be framed by any site.

Analysis

The stored XSS could execute in an agent’s browser and submit privileged actions. Because authentication cookies are available to the browser, the attacker may not need to steal the cookie. The absence of CSRF protection allows a malicious site to cause actions such as changing ticket assignment, provided the victim is logged in. The unrestricted framing policy creates an opportunity for clickjacking on administrative pages. The external script creates a supply-chain dependency with access to ticket content and user interactions.

Approach and Solution

The development team first separates plain-text replies from approved rich text. Plain-text content is inserted using `textContent`; rich text is processed through a maintained sanitizer with a narrowly defined allowlist. The team adds a nonce-based CSP, removes unnecessary inline scripts, and establishes a process for investigating CSP reports.

For state-changing API operations, the server introduces session-bound CSRF tokens and requires them in a custom request header. Cookies are configured with `Secure`, `HttpOnly`, and an appropriate `SameSite` value. The API rejects unsafe requests with missing or invalid tokens. `GET` endpoints are reviewed to ensure they do not change state.

The application adds `frame-ancestors 'none'` to pages that should never be embedded and uses a compatible `X-Frame-Options` policy where required. CORS is restricted to the known front-end origin, and credentialed access is enabled only for endpoints that genuinely require it.

The analytics script is replaced with a pinned version loaded from an approved source using SRI, and its access is reviewed. Unnecessary third-party libraries are removed. Dependency versions are locked and checked during continuous integration.

Outcome

Subsequent testing shows that ticket content is displayed as data, unauthorized cross-site requests are rejected, administrative pages cannot be framed, and the front end no longer trusts arbitrary external script locations. The controls do not eliminate all risk, but they substantially reduce the probability and impact of browser-based attacks.

Learning Points

The case demonstrates that no single control is sufficient. Output safety, CSP, CSRF protection, cookie attributes, framing restrictions, CORS, and dependency governance address different failure modes. It also shows why security decisions must include both application code and the surrounding browser configuration.

Challenges, Limitations, and Common Mistakes

A frequent mistake is to escape all output with one universal function. Encoding is context-specific, and a value safe in HTML text may remain dangerous in a URL or script context. Another mistake is to rely on a CSP that contains broad source allowances while neglecting the original injection flaw.

Teams sometimes treat CORS as an API firewall. It is not: it mainly controls browser read access. Similarly, `HttpOnly` cookies reduce script-based cookie theft but do not prevent XSS from performing actions through the active session. SameSite cookies reduce many CSRF scenarios but do not remove the need for robust authorization and, in sensitive systems, explicit CSRF tokens.

Disabling security controls for convenience is another organizational risk. Developers may permit all origins during development and accidentally carry that configuration into production. They may also publish API keys in front-end code, assuming that minification provides secrecy. Anything delivered to the browser should be considered observable by the user.

Security controls can create compatibility and operational challenges. CSP may break legitimate integrations, strict cookie policies may affect authentication flows, and dependency pinning may delay security updates. These are governance and testing problems, not reasons to abandon the controls. Policies should be introduced deliberately, monitored, and revised according to documented risk decisions.

Ethical, Governance, and Professional Considerations

Front-end security protects more than technical assets. It protects users from unauthorized transactions, privacy loss, manipulation, and reputational harm. Organizations should collect only the client-side data needed for a legitimate purpose and should assess third-party scripts for privacy, security, and contractual implications.

Security governance should assign ownership for headers, dependencies, domains, cookies, and third-party integrations. Changes to analytics tags or embedded content deserve review because they can alter the application’s trust model without changing the primary source code. Vulnerability disclosure processes should provide a responsible way for researchers and users to report browser security problems.

Professional practice also requires honest communication. A team should not claim that a product is “secure” merely because it uses HTTPS, a framework, or a security header. Security is a risk-management activity involving controls, testing, monitoring, and continuous improvement.

Current Developments and Emerging Practices

Modern browser defenses increasingly emphasize restrictive policies, isolation, and explicit permissions. CSP deployment is becoming more systematic through reporting and automated policy analysis. Trusted Types can help prevent DOM XSS by requiring dangerous DOM operations to receive approved, policy-created values. Cross-origin isolation mechanisms, including appropriate use of COOP and COEP, support stronger isolation for applications that need advanced browser capabilities.

Software supply-chain security is also moving toward provenance, signed artifacts, reproducible builds, and automated dependency risk assessment. These practices improve confidence in how front-end assets were produced, although they do not replace code review or least privilege.

AI-assisted code generation introduces additional front-end risk. Generated code may use unsafe DOM sinks, overbroad CORS settings, insecure token storage, or unreviewed dependencies. AI tools can support code analysis and testing, but generated security-sensitive code requires human review, threat modeling, and verification against the application’s actual trust boundaries.

Best-Practice Checklist

A secure front end should normally follow these practices:

  • Treat all external data and third-party code as untrusted until explicitly justified.
  • Prefer framework auto-escaping and safe DOM APIs such as `textContent`.
  • Encode output for its exact context and sanitize only when controlled rich text is required.
  • Deploy a restrictive, monitored CSP and consider Trusted Types for DOM-heavy applications.
  • Use CSRF tokens, suitable SameSite cookies, and server-side authorization for state changes.
  • Configure cookies with `Secure`, `HttpOnly`, narrow scope, and an appropriate `SameSite` policy.
  • Restrict framing with `frame-ancestors` and compatible legacy headers where necessary.
  • Define CORS origins, methods, headers, and credential use explicitly.
  • Minimize third-party scripts, pin dependencies, use lockfiles, and apply SRI where suitable.
  • Keep secrets out of browser code and treat all client-side data as user-observable and modifiable.
  • Test deployed headers, storage, origins, injection points, and dependency behavior continuously.

Chapter Summary

Browser security depends on controlling how data, code, credentials, and authority move across origins and trust boundaries. XSS is mitigated through context-appropriate encoding, safe DOM APIs, careful sanitization, CSP, and reduction of dangerous execution paths. CSRF is addressed through session-bound tokens, SameSite cookies, suitable HTTP methods, and server-side authorization. Clickjacking requires framing restrictions, while secure cookie attributes and cautious storage choices reduce exposure of credentials. CORS must be narrowly configured and must not be mistaken for authentication. Finally, third-party scripts and dependencies create supply-chain risks that require inventory, review, pinning, integrity checks, and least privilege. Effective front-end security is therefore a layered engineering and governance discipline rather than a single configuration task.

Key Terms

Cross-site scripting (XSS): Injection of unintended script that executes in a trusted application’s browser context.

Reflected XSS: XSS in which attacker-controlled input is immediately returned in a response.

Stored XSS: XSS in which malicious content is persisted and later displayed to users.

DOM-based XSS: XSS caused by unsafe client-side manipulation of attacker-controlled data.

Output encoding: Transforming data so that it remains data in a particular interpreter context.

Sanitization: Removing or neutralizing disallowed content while retaining an approved subset of markup.

Content Security Policy (CSP): A browser policy restricting permitted resource sources and execution behavior.

Cross-site request forgery (CSRF): Causing a victim’s browser to submit an authenticated unwanted request.

SameSite: A cookie attribute controlling whether cookies are sent in cross-site contexts.

HttpOnly: A cookie attribute preventing ordinary JavaScript from reading the cookie.

Secure: A cookie attribute restricting transmission to HTTPS connections.

Clickjacking: Deceptive framing or interface manipulation that induces unintended user clicks.

CORS: A mechanism allowing servers to control browser read access from other origins.

Origin: The combination of scheme, host, and port identifying a web security context.

Same-origin policy: Browser restrictions on reading or interacting with resources from another origin.

Subresource Integrity (SRI): A browser mechanism that verifies an external resource against an expected hash.

Supply-chain risk: Security exposure introduced through dependencies, vendors, build systems, or third-party code.

Trusted Types: A browser security mechanism that can restrict dangerous DOM operations to approved values.

Review Questions

Short Answer Questions

1. What three components define a web origin?

2. Distinguish reflected XSS from stored XSS.

3. Why is `textContent` generally safer than `innerHTML` for displaying plain text?

4. What protection does the `HttpOnly` cookie attribute provide?

5. Why does CORS not replace server-side authorization?

Long Answer Questions

1. Explain the browser security model and discuss how the same-origin policy, CORS, and cookies interact.

2. Describe a layered strategy for preventing XSS in a single-page application.

3. Explain CSRF, including synchronizer tokens, SameSite cookies, and the importance of safe HTTP method design.

4. Discuss the security and governance implications of third-party front-end dependencies.

5. Design a secure front-end security workflow covering development, testing, deployment, and monitoring.

Analytical / Application Questions

1. A web application stores access tokens in `localStorage`, renders user comments with `innerHTML`, and permits `Access-Control-Allow-Origin: *`. Identify the major risks and propose a prioritized remediation plan.

2. An organization needs to embed its reporting dashboard in an approved partner portal but nowhere else. Which framing, CORS, and authentication controls should be considered, and why?

3. A customer-support page loads five analytics scripts and uses cookie authentication for state-changing API calls. Analyze the trust boundaries and recommend controls for XSS, CSRF, supply-chain, and privacy risks.

22. Multiple Choice Questions with Answers

Question 1

Which situation best represents DOM-based XSS?

A. A malicious value is stored in a database and displayed in a later response.

B. A query parameter is reflected directly into server-generated HTML.

C. Client-side JavaScript reads a URL fragment and assigns it to innerHTML.

D. An attacker sends a request to an API from a non-browser client.

Correct Answer: C. Client-side JavaScript reads a URL fragment and assigns it to innerHTML.

Question 2

Why is output encoding context-sensitive?

A. Different interpreters parse HTML, JavaScript, CSS, and URLs according to different rules.

B. Encoding is required only when data comes from a database.

C. All encoding methods provide identical protection in every browser context.

D. Context-sensitive encoding applies only to encrypted data.

Correct Answer: A. Different interpreters parse HTML, JavaScript, CSS, and URLs according to different rules.

Question 3

Which control most directly prevents a page from being embedded by unauthorized origins?

A. Access-Control-Allow-Origin

B. Content-Security-Policy frame-ancestors

C. HttpOnly

D. Subresource Integrity

Correct Answer: B. Content-Security-Policy frame-ancestors

Question 4

A cookie-authenticated application needs protection for a money-transfer operation. Which is the strongest appropriate approach?

A. Use a GET request without any additional validation.

B. Rely only on hiding the transfer form with CSS.

C. Use a server-validated CSRF token together with suitable cookie controls and authorization.

D. Store the session identifier in a public JavaScript variable.

Correct Answer: C. Use a server-validated CSRF token together with suitable cookie controls and authorization.

Question 5

What is the primary purpose of the HttpOnly cookie attribute?

A. To prevent the cookie from being sent over HTTPS.

B. To prevent ordinary JavaScript from reading the cookie.

C. To allow the cookie to be sent to every origin.

D. To guarantee that CSRF is impossible.

Correct Answer: B. To prevent ordinary JavaScript from reading the cookie.

Question 6

Which CORS configuration is generally the most appropriate for a credentialed request?

A. Allow every origin with a wildcard and credentials.

B. Reflect every Origin header without validation.

C. Permit a specifically approved origin and enable credentials only when required.

D. Disable authentication because CORS provides it.

Correct Answer: C. Permit a specifically approved origin and enable credentials only when required.

Question 7

What does Subresource Integrity primarily provide?

A. Verification that an external resource matches an expected cryptographic hash.

B. Encryption of all browser storage.

C. Authorization of users performing administrative actions.

D. Automatic prevention of all XSS vulnerabilities.

Correct Answer: A. Verification that an external resource matches an expected cryptographic hash.

Question 8

Why can storing a long-lived bearer token in localStorage increase XSS impact?

A. localStorage automatically sends the token to every server.

B. Any script executing in the origin may be able to read the token.

C. localStorage disables the same-origin policy.

D. localStorage forces the token to be included in image requests.

Correct Answer: B. Any script executing in the origin may be able to read the token.

Question 9

Which statement about CSP is most accurate?

A. CSP makes output encoding unnecessary.

B. CSP is a defense-in-depth policy that can restrict script execution and resource loading.

C. CSP applies only to server-to-server communication.

D. CSP automatically validates all business authorization decisions.

Correct Answer: B. CSP is a defense-in-depth policy that can restrict script execution and resource loading.

Question 10

A team allows arbitrary third-party scripts because they are loaded over HTTPS. What is the main remaining concern?

A. HTTPS prevents the script from accessing the page DOM.

B. The script may still execute with the page’s trust and access sensitive content or interactions.

C. The browser will automatically sandbox the script as an untrusted image.

D. The script cannot change application behavior if it comes from a CDN.

Correct Answer: B. The script may still execute with the page’s trust and access sensitive content or interactions.

Web Application Security and Secure Coding
Chapter 8 of 14