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.
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.
| Category | Angular Control | Remaining Gap | Status |
|---|---|---|---|
| A01 Broken Access Control | Route guards (CanActivate, CanMatch) | Guards protect navigation only. Lazy-loaded bundles still download. Server must enforce authorization on every request. | Complementary |
| A02 Cryptographic Failures | Interceptors can enforce HTTPS; Angular forms obscure credentials from UI | environment.ts is client-side source. All values are accessible in DevTools. API keys must not appear in any Angular source file. | Complementary |
| A03 Injection | Template sanitization; DomSanitizer; Trusted Types; AOT compilation | bypassSecurityTrust* methods and direct DOM access via ElementRef.nativeElement bypass all built-in protections. | Addressed |
| A04 Insecure Design | Dependency injection centralizes auth services | Interceptor chain design and consistent auth service usage are not enforced by the framework. Code review and lint rules are required. | Complementary |
| A05 Security Misconfiguration | Nonce-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 Components | None built in | Committed lockfiles, npm ci in CI, disabled lifecycle scripts, behavioural package scanning, major-version adoption cooldown. | Gap |
| A07 Authentication Failures | HttpClient CSRF; interceptors for auth token injection | Session lifetime, MFA, account lockout, and credential rotation are entirely the application's responsibility. | Complementary |
| A08 Software & Data Integrity Failures | None built in | Subresource Integrity for CDN assets, signed releases, and behavioural package scanning must be enforced at CI level. | Gap |
| A09 Logging & Monitoring Failures | None built in | Angular provides no structured logging. Custom ErrorHandler and HTTP interceptors must be implemented. | Gap |
| A10 SSRF | Angular SSR validates forwarded headers; interceptor-based URL allowlisting | Client-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.
{
"projects": {
"my-app": {
"architect": {
"build": {
"options": {
"optimization": true,
"security": {
"autoCsp": {
"unsafeEval": false
}
}
}
}
}
}
}
}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'<!-- 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.
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.{
"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."
}
]
}
}// 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.
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*.{
"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.
// 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.
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.
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
ignore-scripts=true
audit-level=moderate# GitHub Actions
- name: Install dependencies
run: npm ci --ignore-scripts
- name: Security audit
run: npm audit --audit-level=moderatePackage 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
ignore-scripts=true
strict-peer-dependencies=trueAngular 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.
| Phase | Duration | Action Required |
|---|---|---|
| Active LTS | 18 months from release | Apply patch updates. Schedule minor updates quarterly. |
| Maintenance | 6 months after Active LTS ends | Plan major version upgrade. Create migration ticket. Begin dependency audit. |
| End of Life | After maintenance window | Upgrade is mandatory. Unresolvable advisories accumulate. Each week of delay increases remediation cost. |
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.
environment.ts, constants files, or any TypeScript source that compiles into the browser bundle. Treat the Angular build output as fully public.| Value | Permitted in environment.ts | Notes |
|---|---|---|
| API base URL | Yes | A public endpoint is not a secret. |
| Feature flags | Yes | Assume all flag values are visible to users. |
| Analytics tracking ID | Yes | Designed for public use. |
| Private API key | No | Proxy all authenticated calls through a backend service. |
| OAuth client secret | No | OAuth flows requiring a client secret must go through a backend. |
| Signing keys / HMAC secrets | No | Signing operations must occur server-side only. |
| Database connection strings | No | More common than expected in Angular monorepos where backend config leaks into shared environment files. Any value that reaches the frontend bundle is public. |
// 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.
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
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);
})
);
};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.
— 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.
| Concern | Route Guard | Server-Side |
|---|---|---|
| Prevent navigation to a URL | Yes — redirects the user | Not needed |
| Prevent data exposure | No — bypassed by direct API call | Yes — enforce on every request |
| Prevent code download | No — bundles still transfer | Not typically applicable |
| Authorize resource access | No — client-side only | Yes — authoritative boundary |
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
| Source | Relevance |
|---|---|
| Angular Security Guide — angular.dev | Official Angular documentation on XSS prevention, CSRF, Trusted Types, CSP nonce configuration |
| OWASP Top 10 — owasp.org | Authoritative reference for the A01–A10 categories used in this guideline |
| Sonatype 2026 State of the Software Supply Chain | Source for 454,648 malicious packages figure, 1.2M cumulative total, 99% npm concentration |
| Socket — Shai-Hulud disclosure | September 2025 self-replicating npm worm: @ctrl/tinycolor origin, 500+ packages affected |
| CERT/CC — VU#534320 | Official advisory for the Shai-Hulud self-replicating worm |
| Socket — Axios compromise | March 2026 Axios npm compromise: WAVESHAPER.V2 implant, UNC1069/BlueNoroff attribution |
| ReversingLabs 2026 SSCS Report | Independent confirmation: 73% increase in malicious open-source package detections in 2025 |
| Mondoo — npm supply chain security analysis | Package manager security comparison including pnpm v11 lifecycle-script blocking defaults |