← Back to Angular, page 10

angular-0193 · Hard senior

What would you check in a security review of an Angular application, and how do Content Security Policy and Trusted Types fit in?

Angular escapes templates and sanitizes risky bindings, but a review also checks bypass calls, direct DOM use, token storage, dependency risk, server headers and the API. A strict Content Security Policy limits what scripts can run, and Trusted Types force dangerous DOM sinks to accept only trusted values, which Angular supports.

Full answer

A review has two parts: the code in the app, and the environment around it (headers, dependencies, server). The front end is the visible part, but real protection must also exist on the server.

Code checklist:

  1. XSS sinks. Search for bypassSecurityTrust, innerHTML on nativeElement, document.write, eval, new Function, insertAdjacentHTML, and [innerHTML] with unvalidated data. Each one needs a justification. Prefer Angular's sanitization, and validate or sanitize with an allowlist library before trusting.
  2. URLs. Links and iframes built from user input must be validated (allow only https: and known hosts). Check target="_blank" links use rel="noopener" (modern browsers imply it, but be explicit for older ones).
  3. Authentication. Where are tokens stored? Prefer in memory or HTTP-only secure cookies (with a BFF) over localStorage. Use the code flow with PKCE. Never log tokens. Check logout clears state.
  4. CSRF. With cookie-based sessions, use SameSite cookies and the CSRF token pattern. Angular's HttpClient reads an XSRF-TOKEN cookie and sends X-XSRF-TOKEN for same-origin mutating requests. Bearer tokens in headers are not sent automatically by the browser, so they avoid classic CSRF.
  5. Data exposure. No secrets in the bundle (API keys that grant write access, private URLs). Everything in the client is public.
  6. Authorization. Guards and hidden buttons are only user experience. Confirm the API enforces access.
  7. Error handling. Do not show stack traces or server messages to users, and do not send personal data to logging tools.

Environment checklist:

  • Dependencies: npm audit, lock files, automated updates, review of new packages, and removal of unused ones.
  • Headers: Content-Security-Policy, X-Content-Type-Options: nosniff, Referrer-Policy, Strict-Transport-Security, frame-ancestors (clickjacking), and correct CORS on the API.

Content Security Policy (CSP): a header that tells the browser which sources of scripts, styles and connections are allowed. A strict CSP (nonce or hash based, no unsafe-inline) means injected inline scripts do not run, which limits XSS damage. Angular supports CSP: set ngCspNonce on the root element (the server provides the nonce per response) so styles that Angular adds are allowed, and the build can inline critical CSS with nonce support.

Trusted Types: a browser feature (require-trusted-types-for 'script') that makes DOM sinks such as innerHTML and script.src accept only special objects, not strings. Angular provides policies (angular, angular#bundler) so its own code works, and a violation shows where untrusted code touches a sink. Start in report-only mode, fix violations, then enforce.

Present findings with severity and fix, and automate checks (lint rules, dependency scans, CSP tests) so the review is repeatable.

typescript
// file: security-headers.ts
export const securityHeaders: Record<string, string> = {
  'Content-Security-Policy':
    "default-src 'self'; script-src 'self' 'nonce-{NONCE}'; style-src 'self' 'nonce-{NONCE}'; " +
    "img-src 'self' data:; connect-src 'self' https://api.example.com; frame-ancestors 'none'; " +
    "require-trusted-types-for 'script'",
  'X-Content-Type-Options': 'nosniff',
  'Referrer-Policy': 'strict-origin-when-cross-origin',
  'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
};

export function headersFor(nonce: string): Record<string, string> {
  return Object.fromEntries(Object.entries(securityHeaders).map(([k, v]) => [k, v.replaceAll('{NONCE}', nonce)]));
}

console.log(headersFor('abc123')['Content-Security-Policy']);

// index.html: <app-root ngCspNonce="abc123"></app-root>

Angular 20.3, type-checked. The XSRF header behaviour was checked in Karma for the earlier CSRF item, not again here. The header helper was run in Node twice with identical output. The CSP header values are an example and were not tested against a browser here.

Key points

  • Review code (bypass calls, DOM sinks, URLs, token storage, secrets) and the environment (dependencies, headers, CORS).
  • Guards are UX. The server enforces authorization.
  • A strict CSP limits script execution. Use `ngCspNonce` with Angular.
  • Trusted Types restrict dangerous sinks, and Angular has policies. Start in report-only mode.

Common mistakes

  • Storing long-lived tokens in `localStorage`.
  • Adding `unsafe-inline` to make a CSP error disappear.
  • Trusting client side checks.

Follow-ups

  • How does Angular's XSRF protection work?
  • What does `ngCspNonce` do?
  • How do you roll out a CSP safely?

Tips

  • Give a structured checklist: code, then environment.
  • Explain CSP and Trusted Types in one sentence each.
  • Mention report-only rollout.

Evaluation rubric

  • Covers code and environment checks.
  • Explains CSP and Trusted Types correctly.
  • Advises a safe rollout and automation.