Angular Security Development Guideline

OWASP A01–A10 mapped to Angular-specific controls with enforceable linting rules, CI gates, and supply chain hardening. Written for enterprise Angular teams building production applications.

Angular's Built-In Protections

Angular establishes a security floor that covers the most common DOM-based attack vectors. Understanding what the framework provides — and where it stops — is the starting point for any team security guideline.

What Angular covers by default
Template sanitization: Angular treats all binding values as untrusted and sanitizes HTML, style, and URL contexts before DOM insertion. Resource URLs (src on scripts and objects) cannot be sanitized and are blocked unless explicitly trusted via DomSanitizer.

AOT compilation: The Ahead-of-Time compiler eliminates template injection at build time. Dynamic template strings cannot carry injected executable code.

CSRF: HttpClient implements the cookie-to-header CSRF pattern (XSRF-TOKEN → X-XSRF-TOKEN) automatically for same-origin requests.

SSR header validation: Angular SSR validates Host, X-Forwarded-Host, X-Forwarded-Proto, X-Forwarded-Prefix, and X-Forwarded-Port to prevent header-based host injection.

Everything below covers what Angular does not enforce automatically.

OWASP A01–A10 Mapping

Addressed: Angular provides the control directly. Complementary: Angular provides partial coverage; team policy closes the gap. Gap: Angular provides nothing; the team must implement entirely.

CategoryAngular ControlRemaining GapStatus
A01 Broken Access ControlRoute guards (CanActivate, CanMatch)Guards protect navigation only. Lazy-loaded bundles still download. Server must enforce authorization on every request.Complementary
A02 Cryptographic FailuresInterceptors can enforce HTTPS; Angular forms obscure credentials from UIenvironment.ts is client-side source. All values are accessible in DevTools. API keys must not appear in any Angular source file.Complementary
A03 InjectionTemplate sanitization; DomSanitizer; Trusted Types; AOT compilationbypassSecurityTrust* methods and direct DOM access via ElementRef.nativeElement bypass all built-in protections.Addressed
A04 Insecure DesignDependency injection centralizes auth servicesInterceptor chain design and consistent auth service usage are not enforced by the framework. Code review and lint rules are required.Complementary
A05 Security MisconfigurationNonce-based CSP via autoCsp; Trusted Types policies (angular, angular#bundler)CSP and Trusted Types are disabled by default. Both must be explicitly configured for every production build.Addressed when configured
A06 Vulnerable & Outdated ComponentsNone built inCommitted lockfiles, npm ci in CI, disabled lifecycle scripts, behavioural package scanning, major-version adoption cooldown.Gap
A07 Authentication FailuresHttpClient CSRF; interceptors for auth token injectionSession lifetime, MFA, account lockout, and credential rotation are entirely the application's responsibility.Complementary
A08 Software & Data Integrity FailuresNone built inSubresource Integrity for CDN assets, signed releases, and behavioural package scanning must be enforced at CI level.Gap
A09 Logging & Monitoring FailuresNone built inAngular provides no structured logging. Custom ErrorHandler and HTTP interceptors must be implemented.Gap
A10 SSRFAngular SSR validates forwarded headers; interceptor-based URL allowlistingClient-side controls cannot prevent SSRF. Server-side request validation is the security boundary.Complementary

CSP and Trusted Types

Angular supports nonce-based Content Security Policy via the autoCsp build option and the ngCspNonce attribute on the application root element. Trusted Types enforcement uses policies named angular, angular#bundler, and angular#unsafe-bypass.

Enforce: CSP and Trusted Types mandatory in production
Both are opt-in and inactive by default. Nonces must be generated at the origin server per-request — never hardcoded. Responses served through a CDN cache must not carry nonce-bearing CSP headers; generate nonces at the edge or serve those responses uncached.
angular.json — autoCsp JSON
{
  "projects": {
    "my-app": {
      "architect": {
        "build": {
          "options": {
            "optimization": true,
            "security": {
              "autoCsp": {
                "unsafeEval": false
              }
            }
          }
        }
      }
    }
  }
}
Content-Security-Policy header HTTP
Content-Security-Policy:
  require-trusted-types-for 'script';
  trusted-types angular angular#bundler;
  script-src 'nonce-{SERVER_NONCE}' 'strict-dynamic';
  object-src 'none';
  base-uri 'none'
index.html — nonce propagation HTML
<!-- Nonce injected server-side per request — never cached -->
<app-root ngCspNonce="{{ .Nonce }}"></app-root>

bypassSecurityTrust* Policy

Angular's DomSanitizer.bypassSecurityTrust* methods — bypassSecurityTrustHtml, bypassSecurityTrustScript, bypassSecurityTrustUrl, bypassSecurityTrustResourceUrl, bypassSecurityTrustStyle — explicitly tell Angular to render a value without sanitization. Each call is a deliberate opt-out of XSS protection.

Enforce: PR-level justification required for every use
Every call to a bypassSecurityTrust* method must carry an inline comment explaining why bypass is necessary, what alternative was considered, and who reviewed it. Block at lint level; allow specific instances via eslint-disable-next-line only after documented security review. Track approved bypass count as a security metric.
ESLint — ban bypassSecurityTrust* at call sites JSON
{
  "rules": {
    "no-restricted-syntax": [
      "error",
      {
        "selector": "CallExpression[callee.property.name=/^bypassSecurityTrust/]",
        "message": "bypassSecurityTrust* bypasses Angular XSS protection. Add an inline justification comment and obtain security review before using eslint-disable."
      }
    ]
  }
}
Approved use — required justification pattern TypeScript
// SECURITY: value is a static SVG asset path assembled from
// an allowlist of known-safe strings. No user input reaches this call.
// Reviewed: security-team 2026-01-15. Ticket: SEC-421.
// eslint-disable-next-line no-restricted-syntax
const safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(
  ALLOWED_ICON_PATHS[iconKey]
);

Direct DOM Access

Native browser DOM APIs do not apply Angular's security model. Code that accesses the DOM directly — via ElementRef.nativeElement, document.getElementById, document.createElement, or innerHTML assignment — bypasses sanitization and Trusted Types enforcement.

Enforce: ban direct DOM access via ESLint
Prohibit ElementRef.nativeElement, raw innerHTML assignment, and document.write in application code. Where direct DOM access is unavoidable (third-party library integration, canvas operations), apply the same approval process as bypassSecurityTrust*.
ESLint — ban innerHTML and nativeElement JSON
{
  "rules": {
    "no-restricted-properties": [
      "error",
      {
        "object": "ElementRef",
        "property": "nativeElement",
        "message": "Direct DOM access via ElementRef.nativeElement bypasses Angular's security model. Use Angular template bindings or Renderer2."
      }
    ],
    "no-restricted-syntax": [
      "error",
      {
        "selector": "AssignmentExpression[left.property.name='innerHTML']",
        "message": "innerHTML assignment bypasses Trusted Types and Angular sanitization. Use [innerHTML] binding with DomSanitizer, or Renderer2."
      },
      {
        "selector": "CallExpression[callee.object.name='document'][callee.property.name='write']",
        "message": "document.write is unsafe and disallowed."
      }
    ]
  }
}

Preferred Alternative: Renderer2

Renderer2 provides a platform-agnostic DOM abstraction that respects Angular's security model and works correctly in SSR contexts.

Renderer2 — safe DOM manipulation TypeScript
// Avoid: direct DOM access
this.elementRef.nativeElement.innerHTML = content;

// Prefer: Renderer2
@Component({ selector: 'app-widget', template: '<div #host></div>' })
export class WidgetComponent {
  @ViewChild('host') host!: ElementRef;
  constructor(private renderer: Renderer2) {}

  addText(text: string): void {
    const node = this.renderer.createText(text);
    this.renderer.appendChild(this.host.nativeElement, node);
  }
}

Supply Chain Security

Supply chain compromise is the highest-growth attack surface for Angular teams in 2025–2026. Standard static analysis and npm audit do not detect it: the attack inserts malicious code into packages that pass all existing checks before publishing.

Threat landscape — cited figures
Sonatype identified 454,648 malicious packages published across npm, PyPI, Maven Central, NuGet, and Hugging Face in 2025, bringing the cumulative total to over 1.2 million. Over 99% of detected open-source malware in 2025 originated on npm. Sonatype 2026 State of the Software Supply Chain Report.

In September 2025, Socket disclosed Shai-Hulud — the first self-replicating worm on a public package registry. Starting from a compromised @ctrl/tinycolor, the worm spread to 500+ packages through credential theft and automated publishing. CERT/CC issued advisory VU#534320. Sources: Socket blog; CERT/CC.

In March 2026, the Axios npm package was compromised with a WAVESHAPER.V2 implant, attributed to UNC1069 (BlueNoroff / Stardust Chollima). Socket's automated detection flagged the malicious package within six minutes of publication. Source: Socket blog, April 2026.

Lazarus Group-associated packages: Sonatype identified 800+ in 2025; Socket's broader attribution tracked 1,700+ across npm and other registries, 97% concentrated on npm.
Enforce: supply chain hardening checklist
1. Commit package-lock.json or pnpm-lock.yaml — never add the lockfile to .gitignore.
2. Use npm ci --ignore-scripts (or pnpm install --frozen-lockfile) in CI — never npm install.
3. Set ignore-scripts=true in .npmrc to disable lifecycle scripts by default.
4. Enforce a 7–14 day cooldown on new major-version adoption — do not update on release day.
5. Integrate Socket or Snyk for behavioural scanning beyond npm audit.
6. Review all transitive dependencies with install scripts before enabling them.
.npmrc — disable lifecycle scripts Shell
# .npmrc
ignore-scripts=true
audit-level=moderate
CI pipeline — frozen install YAML
# GitHub Actions
- name: Install dependencies
  run: npm ci --ignore-scripts

- name: Security audit
  run: npm audit --audit-level=moderate

Package Manager Evaluation

pnpm has been building consumer-side security controls since v10. As of v11 (April 2026), it ships lifecycle-script blocking and release cooldown enforcement as opt-in defaults — making it the first major package manager to operationalize supply chain defence at install time. Angular teams should evaluate pnpm as the default package manager for new projects. Migration cost is low but non-zero: validate ng build and ng serve compatibility, update CI install scripts to pnpm install --frozen-lockfile, and confirm that any Angular CLI schematics resolve correctly under pnpm's stricter hoisting rules.

pnpm .npmrc — security defaults Shell
# pnpm .npmrc
ignore-scripts=true
strict-peer-dependencies=true

Angular Version Currency

Running npm audit on an Angular project more than two major versions behind current typically surfaces advisories that cannot be resolved without upgrading the framework itself — peer dependency constraints prevent patching individual packages in isolation.

Enforce: stay within one major version of current
Define a maximum acceptable age for each major version before upgrade is mandatory. Once a version reaches end-of-life, unresolvable advisory counts grow and patching individual packages requires forking at significant maintenance cost.
PhaseDurationAction Required
Active LTS18 months from releaseApply patch updates. Schedule minor updates quarterly.
Maintenance6 months after Active LTS endsPlan major version upgrade. Create migration ticket. Begin dependency audit.
End of LifeAfter maintenance windowUpgrade is mandatory. Unresolvable advisories accumulate. Each week of delay increases remediation cost.
Angular update tooling
Use ng update @angular/core @angular/cli to perform guided major version migrations. The CLI runs schematics that automate most breaking-change adaptations. Review the BREAKING CHANGES section of each release changelog manually — automated migration covers most changes, not all.

Secrets and Environment Files

Angular's environment.ts and environment.prod.ts files are TypeScript source code compiled into the application bundle. Everything in them is accessible to any user who opens DevTools. There is no obfuscation mechanism that makes this safe.

Enforce: zero secrets in Angular source files
API keys, private credentials, signing keys, and service tokens must never appear in environment.ts, constants files, or any TypeScript source that compiles into the browser bundle. Treat the Angular build output as fully public.
ValuePermitted in environment.tsNotes
API base URLYesA public endpoint is not a secret.
Feature flagsYesAssume all flag values are visible to users.
Analytics tracking IDYesDesigned for public use.
Private API keyNoProxy all authenticated calls through a backend service.
OAuth client secretNoOAuth flows requiring a client secret must go through a backend.
Signing keys / HMAC secretsNoSigning operations must occur server-side only.
Database connection stringsNoMore common than expected in Angular monorepos where backend config leaks into shared environment files. Any value that reaches the frontend bundle is public.
Secure backend proxy pattern TypeScript
// Correct: Angular calls your own API; server holds the credential
@Injectable({ providedIn: 'root' })
export class GeocodeService {
  constructor(private http: HttpClient) {}

  geocode(address: string): Observable<GeoResult> {
    return this.http.get<GeoResult>('/api/geocode', { params: { address } });
  }
}

// Incorrect: private key visible in DevTools source tab
// const MAPS_KEY = 'AIza...';
// return this.http.get('https://maps.api.com?key=' + MAPS_KEY);

HTTP Interceptors as a Security Layer

Angular HTTP interceptors inspect and transform every outgoing request and incoming response. They are the correct place to enforce authentication token injection, CSRF header attachment, response error handling, and outbound URL validation.

Standard interceptor chain
Define and document a standard interceptor chain for every application. At minimum:
1. URL allowlist — block requests to non-allowlisted origins
2. Auth token injection — attach Bearer token to authorized requests
3. CSRF header — attach CSRF token to mutating requests
4. Error handler — normalize 401/403 responses and trigger auth flows
security.interceptor.ts — URL allowlist + auth token + error handling TypeScript
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { catchError, throwError } from 'rxjs';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';

// Provide this token in app.config.ts so the allowlist works in both
// browser and SSR environments (window is not available server-side).
export const APP_ORIGIN = new InjectionToken<string>('APP_ORIGIN');

const EXTRA_ALLOWED_ORIGINS: ReadonlySet<string> = new Set([
  'https://api.example.com',
]);

export const securityInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  const router = inject(Router);
  const platformId = inject(PLATFORM_ID);
  // APP_ORIGIN must be provided; fallback to empty string suppresses
  // window access in SSR and causes all non-relative URLs to be blocked.
  const appOrigin = inject(APP_ORIGIN, { optional: true }) ?? '';
  const allowed = new Set([appOrigin, ...EXTRA_ALLOWED_ORIGINS]);

  try {
    const base = isPlatformBrowser(platformId) ? window.location.origin : appOrigin;
    const url = new URL(req.url, base);
    if (!allowed.has(url.origin)) {
      return throwError(() => new Error('Request to disallowed origin: ' + url.origin));
    }
  } catch {
    return throwError(() => new Error('Malformed request URL: ' + req.url));
  }

  const token = auth.getAccessToken();
  const secured = token
    ? req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) })
    : req;

  return next(secured).pipe(
    catchError((err: unknown) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) auth.clearSession();
        if (err.status === 401 || err.status === 403) {
          router.navigate(['/login'], { queryParams: { returnUrl: router.url } });
        }
      }
      return throwError(() => err);
    })
  );
};
app.config.ts — register interceptor TypeScript
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { securityInterceptor, APP_ORIGIN } from './security.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    // Provide the app's own origin so the interceptor works in SSR
    // (window.location is not available server-side).
    { provide: APP_ORIGIN, useValue: 'https://app.example.com' },
    provideHttpClient(withInterceptors([securityInterceptor])),
  ],
};

Route Guards vs. Server-Side Authorization

Angular route guards (CanActivate, CanActivateChild, CanMatch) prevent navigation to protected routes when conditions are not met. They are a UX mechanism, not a security boundary.

Critical: guards do not protect data or code
Route guards block navigation in the browser. They do not prevent:
— Lazy-loaded module bundles from downloading to the browser
— Direct HTTP requests to API endpoints
— An attacker reading guarded component code from the application bundle

Authorization must be enforced server-side on every API request, regardless of what any client-side guard does. Guards improve UX by redirecting unauthorized users; they cannot replace server-side access control.
ConcernRoute GuardServer-Side
Prevent navigation to a URLYes — redirects the userNot needed
Prevent data exposureNo — bypassed by direct API callYes — enforce on every request
Prevent code downloadNo — bundles still transferNot typically applicable
Authorize resource accessNo — client-side onlyYes — authoritative boundary
auth.guard.ts — navigation UX, not security boundary TypeScript
import { CanActivateFn } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';

// Improves UX by redirecting unauthenticated users.
// Does NOT secure data or API — server-side auth is the boundary.
export const authGuard: CanActivateFn = (_route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (auth.isAuthenticated()) return true;

  return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url }
  });
};

References

SourceRelevance
Angular Security Guide — angular.devOfficial Angular documentation on XSS prevention, CSRF, Trusted Types, CSP nonce configuration
OWASP Top 10 — owasp.orgAuthoritative reference for the A01–A10 categories used in this guideline
Sonatype 2026 State of the Software Supply ChainSource for 454,648 malicious packages figure, 1.2M cumulative total, 99% npm concentration
Socket — Shai-Hulud disclosureSeptember 2025 self-replicating npm worm: @ctrl/tinycolor origin, 500+ packages affected
CERT/CC — VU#534320Official advisory for the Shai-Hulud self-replicating worm
Socket — Axios compromiseMarch 2026 Axios npm compromise: WAVESHAPER.V2 implant, UNC1069/BlueNoroff attribution
ReversingLabs 2026 SSCS ReportIndependent confirmation: 73% increase in malicious open-source package detections in 2025
Mondoo — npm supply chain security analysisPackage manager security comparison including pnpm v11 lifecycle-script blocking defaults