Angular Security
Why this matters
Section titled “Why this matters”Angular gives you strong defaults against one specific class of attack — cross-site scripting through template rendering — and nothing at all against most others. The dangerous gap is not knowing which is which. Developers routinely believe “Angular sanitizes everything” and then hold authorisation checks in a guard, put an API key in an environment file, and call bypassSecurityTrustHtml on a CMS field.
This page covers what the framework actually protects, how to extend that protection with platform features, and the application-level concerns Angular explicitly does not address.
What Angular does and does not cover
Section titled “What Angular does and does not cover”Angular’s security documentation is clear about its own scope: it covers built-in protections against common web vulnerabilities such as XSS, and it does not cover application-level security such as authentication and authorisation.
| Concern | Angular’s role |
|---|---|
| XSS via template bindings | Handled — automatic contextual sanitization |
| Template injection | Handled — by using the AOT compiler |
| XSSI | Client half — strips the )]}',\n prefix |
| XSRF | Client half — cookie-to-header token |
| Authentication | None |
| Authorisation | None — guards are UX, not security |
| Secret management | None — everything shipped is public |
| Server-side input validation | None |
| Dependency vulnerabilities | Your responsibility |
| CSP / Trusted Types | Supported, but you must configure the server |
Angular’s XSS security model
Section titled “Angular’s XSS security model”Angular treats all values as untrusted by default. When a value reaches the DOM through interpolation or a template binding, Angular sanitizes and escapes it.
Templates, in contrast, are trusted by default and treated as executable code. That asymmetry is the single most important thing to understand: never build a template by concatenating user input with template syntax. Doing so is arbitrary code injection with extra steps.
Sanitization contexts
Section titled “Sanitization contexts”Sanitization is context-dependent — a value that is harmless in CSS can be dangerous in a URL. Angular defines four contexts:
| Context | Applies to | Sanitized? |
|---|---|---|
| HTML | [innerHTML] and similar |
Yes |
| Style | Binding CSS into style |
Contextual |
| URL | <a href> and similar |
Yes |
| Resource URL | <script src>, <iframe src> — loaded and executed as code |
No — impossible |
Resource URLs cannot be sanitized because they name arbitrary code to fetch and run. There is no transformation that makes an attacker-chosen script URL safe. That is why binding a dynamic value into <iframe src> requires an explicit trust call, and why that call is genuinely dangerous.
In development mode, Angular logs a console warning whenever sanitization changed a value. Those warnings are worth reading rather than filtering out — each one is a place where untrusted data reached a rendering context.
Interpolation versus innerHTML
Section titled “Interpolation versus innerHTML”<!-- Escaped. The browser shows the angle brackets as text. Always safe. --><p>{{ htmlSnippet }}</p>
<!-- Interpreted as HTML. Sanitized, but this is where XSS lives. --><p [innerHTML]="htmlSnippet"></p>Given Template <script>alert("XSS")</script> <b>Syntax</b>, interpolation displays the literal text. The [innerHTML] binding renders it as HTML with the <script> removed and the <b> kept.
XSS is not limited to <script> tags. <img alt="" onerror="..."> and <a href="javascript:..."> both execute code, and many other elements and attributes do too. Angular’s sanitizer knows these; a hand-rolled “strip <script>” filter does not.
Prefer interpolation. Reach for [innerHTML] only when you genuinely need to render markup, and even then, know that you are relying entirely on the sanitizer.
Bypassing sanitization
Section titled “Bypassing sanitization”Sometimes you legitimately need an <iframe>, an SVG, or a URL Angular would strip. DomSanitizer provides the escape hatches:
bypassSecurityTrustHtmlbypassSecurityTrustScriptbypassSecurityTrustStylebypassSecurityTrustUrlbypassSecurityTrustResourceUrl
Angular’s own wording is unusually direct: “If you trust a value that might be malicious, you are introducing a security vulnerability into your application. If in doubt, find a professional security reviewer.”
The safe pattern is to validate before trusting, never to trust and hope:
@Service()export class VideoEmbed { private readonly sanitizer = inject(DomSanitizer);
embedUrl(videoId: string): SafeResourceUrl { // Validate the shape first. The id is the only user-supplied part, // and it is constrained to a known-safe character set. if (!/^[A-Za-z0-9_-]{6,20}$/.test(videoId)) { throw new Error('Invalid video id'); } return this.sanitizer.bypassSecurityTrustResourceUrl( `https://videos.example.test/embed/${videoId}`, ); }}Note what makes this defensible: the origin is a constant in your code, and the only variable part is validated against an allowlist pattern. Compare with the version that is not defensible:
// Never do this. The entire URL comes from data you do not control.trustedUrl(url: string): SafeResourceUrl { return this.sanitizer.bypassSecurityTrustResourceUrl(url);}Rules of thumb for any bypass call:
- Choose the narrowest context.
bypassSecurityTrustUrlis notbypassSecurityTrustResourceUrl; the latter permits code execution. - Never bypass a value that originated from user input, an API, or a CMS without validating its structure first.
- Keep bypasses in one small, reviewed module. They should be greppable and countable, not scattered.
- Never call a bypass in a template or a getter. It runs on every check, and it hides the decision from review.
- Use
DomSanitizer.sanitize(context, value)when you need explicit sanitization outside a binding — it also passes through values already marked trusted.
Content Security Policy
Section titled “Content Security Policy”CSP is defence in depth at the DOM level, where it cannot be bypassed by lower-level APIs. Angular strongly encourages it.
The minimal policy for a new Angular application:
default-src 'self'; style-src 'self' 'nonce-randomNonceGoesHere'; script-src 'self' 'nonce-randomNonceGoesHere';Angular inserts <style> elements at runtime, so it needs the nonce. Three ways to supply it:
autoCsp: truein the workspace configuration.ngCspNonceon the root element:<app ngCspNonce="randomNonceGoesHere"></app>. Use this when server-side templating can add the nonce to both the header andindex.html.- The
CSP_NONCEinjection token, when the nonce is available at runtime and you want to cacheindex.html:
bootstrapApplication(App, { providers: [{ provide: CSP_NONCE, useValue: globalThis.myRandomNonceValue }],});Nonces and caching — the failure nobody expects
Section titled “Nonces and caching — the failure nobody expects”Angular’s callout on this deserves repeating, because it is a real-world CSP bypass that looks like it is working:
Nonces must be unique per request and unpredictable. If an attacker can predict future nonces, CSP protection is gone.
Generating the nonce at the origin server is discouraged when a CDN is in front of it. If the server generates a nonce and the CDN caches that HTML response, every subsequent visitor receives the same “unique” value — an attacker can simply read it and use it. To preserve one-time-use, generate the nonce at the edge, immediately before delivery.
One more interaction: if you inline critical CSS, you cannot use the CSP_NONCE token — use autoCsp or the ngCspNonce attribute instead.
If you cannot generate nonces at all, 'unsafe-inline' in style-src is the fallback, at the cost of a meaningfully weaker policy.
Trusted Types
Section titled “Trusted Types”Trusted Types is a browser feature that prevents DOM-based XSS by requiring dangerous DOM sinks to receive typed, policy-approved values rather than strings. Angular supports it and recommends it.
Enforce it with a header:
Content-Security-Policy: trusted-types angular; require-trusted-types-for 'script';Angular’s policies, and when each is required:
| Policy | Required when |
|---|---|
angular |
Always — Angular needs it to function under enforcement |
angular#bundler |
The CLI bundler creates lazy chunk files (so: lazy loading) |
angular#unsafe-bypass |
The application uses any DomSanitizer bypass method |
angular#unsafe-jit |
The application uses the JIT compiler |
angular#unsafe-upgrade |
The application is an AngularJS hybrid via @angular/upgrade |
Configure the header in production serving infrastructure, in angular.json’s headers property for ng serve, and in the Karma config for tests if you are still on Karma.
Two properties worth knowing. Browsers without Trusted Types support lose nothing — the application still works, guarded by Angular’s DomSanitizer. And needing angular#unsafe-bypass is itself useful information: it makes “this application bypasses sanitization somewhere” visible in the security header, which is a good forcing function for review.
AOT and template injection
Section titled “AOT and template injection”The AOT compiler prevents an entire vulnerability class: template injection. It is the default for CLI applications and should be used in every production deployment.
The JIT compiler compiles templates in the browser at runtime. Because Angular trusts template code, dynamically generating a template that contains user data and compiling it hands the attacker full control of the application. Angular calls this a security anti-pattern in plain terms. For genuinely dynamic forms, use the dynamic forms approach — build a data-driven form model, never a template string.
The server-side counterpart: do not generate Angular templates on the server with a templating language. Injecting template code into an Angular application is equivalent to injecting executable code. Use a server-side templating language that escapes automatically, and keep Angular templates out of it.
HTTP-level protections
Section titled “HTTP-level protections”Angular helps with two HTTP vulnerabilities, and in both cases the mitigation is primarily server-side — Angular provides the client half.
XSRF / CSRF
Section titled “XSRF / CSRF”The attack: a user logged in to your application visits an attacker’s page, which fires a request at your server. The browser attaches the user’s cookies automatically, so without protection the server cannot distinguish that forged request from a legitimate one.
The defence Angular implements is the cookie-to-header token pattern. An interceptor reads a token from a cookie (default XSRF-TOKEN) and sets it as a header (default X-XSRF-TOKEN) on mutating same-origin requests. Because the same-origin policy prevents another site reading that cookie, a matching header is evidence the request came from your application.
provideHttpClient( withXsrfConfiguration({ cookieName: 'CSRF-TOKEN', headerName: 'X-CSRF-TOKEN' }),);The requirements, all of which are on the server:
- Set the cookie on page load or the first
GET. - Verify the header on every eligible request; reject when missing or mismatched.
- Make the token unique per user and verifiable — the documentation suggests a digest of the site’s authentication cookie plus a salt — so a client cannot invent one.
- Give each application a distinct cookie name where several share a domain or subdomain.
GET and HEAD are excluded deliberately: CSRF only matters for state-changing requests, and the same-origin policy already prevents an attacking page reading an authenticated GET response.
Without the server side, Angular’s default protection is ineffective. It is client-half only.
Cross-Site Script Inclusion loads your JSON endpoint as a <script> on an attacker’s page. The standard defence is a non-executable prefix on JSON responses, conventionally )]}',\n, so the body is not valid JavaScript. HttpClient strips this automatically when parsing JSON — your server has to emit it.
Application-level security Angular does not provide
Section titled “Application-level security Angular does not provide”This is the part that causes real incidents.
Authorisation. A route guard decides whether to render a screen. It does not stop anyone calling the API. All client JavaScript can be modified by the person running the browser, and a lazy chunk gated by canMatch is still a file anyone can request from your origin. Every authorisation decision is enforced server-side, on every request.
Secrets. Anything in the client bundle is public: environment files, InjectionToken values, interceptor constants, .env values inlined at build time. There is no such thing as a hidden API key in a browser application. Secrets live on a server the client calls.
Token storage. localStorage is readable by any JavaScript on the origin, so one XSS becomes total account compromise. httpOnly, Secure, SameSite cookies are not readable by script, which is why they are the stronger default — at the cost of needing XSRF protection, which is the trade the previous section describes. In-memory storage is safest against exfiltration and is lost on refresh. Whatever you choose, keep access-token lifetimes short.
Input validation. Client validation is fast feedback for honest users. The server validates independently, always.
Open redirects. Validate ?returnUrl= before navigating to it. Accept same-origin relative paths only, and reject //host — a protocol-relative URL to another origin that starts with a slash.
Data in URLs. Query strings land in browser history, server and proxy logs, analytics, and the Referer header sent to third parties. No tokens, session ids, reset codes or personal identifiers.
Dependencies. Run npm audit in CI. Keep Angular current — Angular’s own first best practice is to stay on recent releases, because updates fix security defects. Do not maintain a private fork of Angular; it falls behind on exactly those fixes.
Reporting. Angular participates in Google’s Open Source Software Vulnerability Reward Program. Report framework vulnerabilities at bughunters.google.com, not in a public issue.
Anti-patterns
Section titled “Anti-patterns”| Anti-pattern | Why it is dangerous |
|---|---|
bypassSecurityTrustHtml on CMS or API content |
Anyone who can edit that content can run script on your origin |
bypassSecurityTrustResourceUrl on a user-supplied URL |
Loads and executes attacker-chosen code |
[innerHTML] used by default |
The sanitizer is your only defence; interpolation needs none |
Hand-rolled “strip <script>” sanitizing |
Misses onerror, javascript: URLs, and dozens of other vectors |
| Building templates from user input, or JIT in production | Template injection — full application compromise |
| Generating Angular templates server-side | Same, from the other direction |
| Guards treated as authorisation | The API is unprotected |
| Secrets in environment files | Published in the bundle |
Tokens in localStorage |
One XSS exfiltrates every session |
'unsafe-inline'/'unsafe-eval' in CSP to “make it work” |
Removes most of CSP’s value |
| Nonces generated at origin behind a caching CDN | Every visitor gets the same nonce; CSP bypassed |
| Ignoring dev-mode sanitization warnings | Each one marks untrusted data reaching a sink |
credentials: 'include' with permissive CORS |
Cross-origin data exposure |
A security checklist
Section titled “A security checklist”Framework
- AOT compilation in production (the CLI default). No JIT.
- No template built from user input, client-side or server-side.
- Every
bypassSecurityTrust*call inventoried, validated, and reviewed. - Interpolation preferred over
[innerHTML]. - Angular kept current; no private fork.
Platform
- CSP with per-request, unpredictable nonces — generated at the edge if a CDN caches HTML.
- Trusted Types enforced, with the right Angular policies for your build.
- HTTPS everywhere, with HSTS.
HTTP
- XSRF wired up on both ends, with a per-user verifiable token and a distinct cookie name.
- XSSI prefix emitted by the server.
- CORS as narrow as the application allows.
Application
- Authorisation enforced server-side on every request.
- No secrets in client code.
- Tokens in
httpOnlySecureSameSitecookies, or in memory; short lifetimes. - Server-side validation of every input.
returnUrland other redirect targets validated against same-origin.- No sensitive data in query strings or client-side logs.
Supply chain
npm auditin CI, with a policy for what blocks a release.- Dependencies reviewed before adoption, and kept updated.
Senior interview scenarios
Section titled “Senior interview scenarios”“Angular sanitizes bindings. Is your application XSS-proof?”
No — it closes the most common path, not all of them. Angular sanitizes untrusted values reaching the DOM through interpolation and bindings, contextually. But templates themselves are trusted and treated as executable code, so any template built from user input is code injection; resource URLs cannot be sanitized at all, which is why <iframe src> needs an explicit trust call; direct DOM manipulation through ElementRef.nativeElement or a third-party library bypasses the sanitizer entirely; and every bypassSecurityTrust* call is a hole you opened deliberately. CSP and Trusted Types are the defence-in-depth layer, because they operate at the DOM level where lower-level APIs cannot route around them.
“When is bypassSecurityTrustResourceUrl acceptable?”
When the origin is a constant in your code and only a constrained, validated component is dynamic — a video id matched against ^[A-Za-z0-9_-]{6,20}$ interpolated into a hard-coded embed URL, for example. It is never acceptable on a URL that arrives whole from user input, an API, or a CMS, because a resource URL is loaded and executed, so trusting one is trusting whoever controls that value to run code on your origin. Practically: keep such calls in one small reviewed module so they can be counted, and note that needing angular#unsafe-bypass in your Trusted Types header makes their existence visible in the security posture.
“Your CSP has per-request nonces and a CDN in front. What could be wrong?”
If the nonce is generated at the origin server and the CDN caches the HTML response, every visitor receives the same nonce — it looks unique in the code and is effectively static in production. An attacker reads it from any response and satisfies the policy. The fix is to generate the nonce at the edge, immediately before delivery, so each response genuinely carries a fresh one. Also worth checking: inlining critical CSS is incompatible with the CSP_NONCE token, so that combination needs autoCsp or the ngCspNonce attribute instead.
“Where do you store the auth token?”
The honest answer is that there is no option without a trade-off. localStorage is readable by any script on the origin, so a single XSS exfiltrates every session — but it survives refresh and is simple. An httpOnly, Secure, SameSite cookie is not readable by script, which removes that exfiltration path, at the cost of being sent automatically and therefore requiring XSRF protection. In-memory is safest against exfiltration and is lost on refresh, so it needs a silent-renew flow. I default to httpOnly cookies plus XSRF, keep access tokens short-lived, and treat “prevent XSS in the first place” as the actual control rather than the storage choice.
“You inherited an application using JIT in production. Why does that matter?” Angular trusts template code — a template is executable, not data. JIT compiles templates in the browser at runtime, so any path that assembles a template from application data becomes arbitrary code injection with full control of the application. AOT eliminates the class entirely, is the CLI default, and is also faster and smaller. If something genuinely needs runtime-configurable UI, the answer is a data-driven form or component model, never a compiled template string. The same reasoning bans generating Angular templates server-side with a templating language.
“Your guards, validation, and permission service are all correct. What have you actually secured?” The user experience, and nothing else. Every one of those runs in code the user controls and can modify. Guards decide what renders; client validation gives fast feedback; a permission service decides which buttons appear. None of them stands between an attacker and the data, because an attacker calls the API directly. The security boundary is the server: authentication, authorisation on every request, and validation of every input. Angular’s documentation is explicit that application-level security — authentication and authorisation — is outside what the framework covers.
Related pages
Section titled “Related pages”- HttpClient and API Integration
- Angular Routing in Depth
- Route Guards
- Angular Forms
- Templates in Angular