Security Best Practices
Angular has built-in protections against common web application vulnerabilities and attacks such as cross-site scripting (XSS). This guide covers Angular’s security features and best practices to keep your applications secure.General Security Guidelines
Keep Angular Updated
Regular updates include security fixes. Check the Angular changelog for security-related updates.
Don't Modify Angular
Private, customized versions fall behind and miss security fixes. Contribute improvements to the community instead.
Avoid Risky APIs
APIs marked “Security Risk” in documentation should be used with extreme caution.
Preventing Cross-Site Scripting (XSS)
Cross-site scripting (XSS) enables attackers to inject malicious code into web pages. This is one of the most common attacks on the web.Angular’s XSS Security Model
Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template binding or interpolation, Angular sanitizes and escapes untrusted values.Security Contexts
Angular defines different security contexts, each with specific sanitization rules:- HTML
- Style
- URL
- Resource URL
Used when interpreting a value as HTML, such as binding to
innerHTML.Sanitization and Trusted Values
Direct DOM Manipulation
When using DOM APIs directly, you must manually sanitize untrusted values:Trusting Safe Values
Sometimes applications genuinely need to include executable code or construct potentially dangerous URLs. UseDomSanitizer methods to mark values as trusted:
Content Security Policy (CSP)
Content Security Policy is a defense-in-depth technique to prevent XSS. Configure your web server to return an appropriateContent-Security-Policy HTTP header.
Minimal CSP Configuration
The minimal policy required for a new Angular application:- Workspace Config
- Application Root
- Runtime Provider
angular.json
Critical: Always ensure that nonces are unique per request and not predictable. If an attacker can predict future nonces, they can circumvent CSP protections.
CSP Policy Breakdown
default-src 'self'
default-src 'self'
Allows the page to load all required resources from the same origin. This is the baseline security policy.
style-src 'self' 'nonce-...'
style-src 'self' 'nonce-...'
Allows the page to:
- Load global styles from the same origin (
'self') - Load styles inserted by Angular with the specified nonce
script-src 'self' 'nonce-...'
script-src 'self' 'nonce-...'
Allows the page to:
- Load JavaScript from the same origin (
'self') - Load scripts inserted by Angular CLI with the specified nonce
- Required if using critical CSS inlining
Trusted Types
Trusted Types is a web platform feature that helps prevent XSS by enforcing safer coding practices. It’s recommended to use Trusted Types with Angular.Configuring Trusted Types
Configure HTTP headers with Angular policies:Angular Trusted Type Policies
angular
Required for all appsUsed in security-reviewed code internal to Angular. Any inline template values or content sanitized by Angular is treated as safe.
angular#bundler
For lazy loadingUsed by Angular CLI bundler when creating lazy chunk files.
angular#unsafe-bypass
For DomSanitizer bypassRequired if using
bypassSecurityTrustHtml, bypassSecurityTrustScript, etc.angular#unsafe-jit
For JIT compilationRequired if using JIT compiler or platform browser dynamic.
AOT Template Compiler
The Ahead-of-Time (AOT) template compiler prevents template injection vulnerabilities and greatly improves performance.HTTP Security
XSRF/CSRF Protection
Angular’sHttpClient has built-in protection against Cross-Site Request Forgery (XSRF/CSRF) attacks:
How XSRF Protection Works
Server Sets Cookie
Server sets a token in a JavaScript-readable cookie called
XSRF-TOKEN on page load or first GET requestClient Sends Header
On mutating requests (POST, PUT, DELETE), the interceptor adds an
X-XSRF-TOKEN header with the token valueWhy this works: Only code from your domain can read the cookie and set the header. Malicious sites cannot access cookies from other domains due to the same-origin policy.
XSSI Protection
Angular automatically protects against Cross-Site Script Inclusion (XSSI) attacks:Server-Side Request Forgery (SSRF) Prevention
Angular includes strict validation for headers to prevent SSRF attacks:Validated Headers
Host and X-Forwarded-Host
Host and X-Forwarded-Host
Validated against a strict allowlist. Cannot contain path separators. Unrecognized hostnames result in CSR page or 400 Bad Request.
X-Forwarded-Port
X-Forwarded-Port
Must be numeric. Non-numeric values are rejected.
X-Forwarded-Proto
X-Forwarded-Proto
Must be
http or https. Other values are rejected.X-Forwarded-Prefix
X-Forwarded-Prefix
Must not start with multiple
/ or \\ and cannot contain . or .. path segments.Security Checklist
General Security
General Security
- Keep Angular updated to the latest stable version
- Review security advisories in Angular changelog
- Never modify Angular’s core files
- Audit all uses of security-sensitive APIs
- Use AOT compilation in production (enabled by default)
XSS Prevention
XSS Prevention
- Never use
innerHTMLwith untrusted data - Sanitize data when using DOM APIs directly
- Only bypass security when absolutely necessary
- Document why security is bypassed for each case
- Avoid dynamically generating templates
CSP and Trusted Types
CSP and Trusted Types
- Implement Content Security Policy headers
- Use unique, unpredictable nonces per request
- Enable Trusted Types enforcement
- Include appropriate Angular policies
- Test CSP in development and staging
HTTP Security
HTTP Security
- Ensure XSRF protection is enabled (default)
- Configure custom XSRF cookies if needed
- Validate all user input on the server
- Use HTTPS in production
- Configure allowed hosts for SSR
Common Vulnerabilities to Avoid
Template Injection
Unsafe DOM Access
Eval and Function Constructor
Unsafe Resource URLs
Reporting Security Vulnerabilities
Next Steps
Continue learning about Angular best practices:
