Security
This article describes Angular's built-in protections against common web-application vulnerabilities and attacks such as cross-site scripting attacks. It doesn't cover application-level security, such as authentication (Who is this user?) and authorization (What can this user do?).
Best practices
- Keep current with the latest Angular library releases. We regularly update the Angular libraries, and these updates may fix security defects discovered in previous versions. Check the Angular change log for security-related updates.
- Don't modify your copy of Angular. Private, customized versions of Angular tend to fall behind the current version and may not include important security fixes and enhancements. Instead, share your Angular improvements with the community and make a pull request.
- Avoid Angular APIs marked in the documentation as “Security Risk.” For more information, see the Trusting safe values section of this page.
Preventing cross-site scripting (XSS)
Cross-site scripting (XSS) enables attackers to inject malicious code into web pages. Such code can then, for example, steal user data (in particular, login data) or perform actions to impersonate the user. This is one of the most common attacks on the web.
To block XSS attacks, you must prevent malicious code from entering the DOM (Document Object Model). For example, if attackers can trick you into inserting a <script> tag in the DOM, they can run arbitrary code on your website. The attack isn't limited to <script> tags-many elements and properties in the DOM allow code execution, for example, <img onerror="..."> and <a href="javascript:...">. If attacker-controlled data enters the DOM, expect security vulnerabilities.
Angular's cross-site scripting security model
To systematically block XSS bugs, Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.
Angular templates are the same as executable code: HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe. This means that applications must prevent values that an attacker can control from ever making it into the source code of a template. Never generate template source code by concatenating user input and templates. To prevent these vulnerabilities, use the offline template compiler, also known as template injection
Sanitization and security contexts
Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM. In many cases, sanitization doesn't change a value at all. Sanitization depends on context: a value that's harmless in CSS is potentially dangerous in a URL.
Angular defines the following security contexts:
- HTML is used when interpreting a value as HTML, for example, when binding to innerHtml.
- Style is used when binding CSS into the style property.
- URL is used for URL properties, such as <a href>.</a>
- Resource URL is a URL that will be loaded and executed as code, for example, in <script src>.
Angular sanitizes untrusted values for HTML, styles, and URLs; sanitizing resource URLs isn't possible because they contain arbitrary code. In development mode, Angular prints a console warning when it has to change value during sanitization.
Direct use of the DOM APIs and explicit sanitization calls
The built-in browser DOM APIs don't automatically protect you from security vulnerabilities. For example, document, the node available through ElementRef, and many third-party APIs contain unsafe methods. In the same way, if you interact with other libraries that manipulate the DOM, you likely won't have the same automatic sanitization as with Angular interpolations. Avoid directly interacting with the DOM and instead use Angular templates where possible.
For cases where this is unavoidable, use the built-in Angular sanitization functions. Sanitize untrusted values with the DomSanitizer.sanitize method and the appropriate SecurityContext. That function also accepts values that were marked as trusted using the bypassSecurityTrust... functions, and will not sanitize them, as described below.
Content security policy
Content Security Policy (CSP) is a defense-in-depth technique to prevent XSS. To enable CSP, configure your web server to return an appropriate Content-Security-Policy HTTP header. Read more about content security policy at An Introduction to Content Security Policy on the HTML5Rocks website.
Use the offline template compiler
The offline template compiler prevents a whole class of vulnerabilities called template injection and greatly improves application performance. Use the offline template compiler in production deployments; don't dynamically generate templates. Angular trusts template code, so generating templates, in particular templates containing user data, circumvent Angular's built-in protections. For information about dynamically constructing forms in a safe way, see the Dynamic Forms guide page.
Server-side XSS protection
HTML constructed on the server is vulnerable to injection attacks. Injecting template code into an Angular application is the same as injecting executable code into the application: it gives the attacker full control over the application. To prevent this, use a templating language that automatically escapes values to prevent XSS vulnerabilities on the server. Don't generate Angular templates on the server side using a templating language; doing this carries a high risk of introducing template-injection vulnerabilities.
Trusting safe values
Sometimes applications genuinely need to include executable code, display a <iframe> from some URL, or construct potentially dangerous URLs. To prevent automatic sanitization in any of these situations, you can tell Angular that you inspected a value, checked how it was generated, and made sure it will always be secure. But be careful. 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.
To mark a value as trusted, inject DomSanitizer and call one of the following methods:
- bypassSecurityTrustHtml
- bypassSecurityTrustScript
- bypassSecurityTrustStyle
- bypassSecurityTrustUrl
- bypassSecurityTrustResourceUrl
Remember, whether a value is safe depends on context, so choose the right context for your intended use of the value. Imagine that the following template needs to bind a URL to a javascript:alert(...) call:
TypeScript Code:
<h4>An untrusted URL:</h4>
<p><a class="e2e-dangerous-url" [href]="dangerousUrl">Click me</a></p>
<h4>A trusted URL:</h4>
<p><a class="e2e-trusted-url" [href]="trustedUrl">Click me</a></p>
Live Demo:
It is just a code snippet explaining a particular concept and may not have any output
See the Pen KYrqEX by w3resource (@w3resource) on CodePen.
Normally, Angular automatically sanitizes the URL, disables the dangerous code, and in development mode, logs this action to the console. To prevent this, mark the URL value as a trusted URL using the bypassSecurityTrustUrl call:
TypeScript Code:
constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousUrl = 'javascript:alert("Hi there")';
this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
Live Demo:
It is just a code snippet explaining a particular concept and may not have any output
See the Pen transition-constructor by w3resource (@w3resource) on CodePen.
If you need to convert user input into a trusted value, use a controller method. The following template allows users to enter a YouTube video ID and load the corresponding video in an <iframe>. The <iframe src> attribute is a resource URL security context, because an untrusted source can, for example, smuggle in file downloads that unsuspecting users could execute. So call a method on the controller to construct a trusted video URL, which causes Angular to allow binding into <iframe src>:
TypeScript Code:
<h4>Resource URL:</h4>
<p>Showing: {{dangerousVideoUrl}}</p>
<p>Trusted:</p>
<iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="videoUrl"></iframe>
<p>Untrusted:</p>
<iframe class="e2e-iframe-untrusted-src" width="640" height="390" [src]="dangerousVideoUrl"></iframe>
Live Demo:
It is just a code snippet explaining a particular concept and may not have any output
See the Pen jRQwvm by w3resource (@w3resource) on CodePen.
TypeScript Code:
updateVideoUrl(id: string) {
// Appending an ID to a YouTube URL is safe.
// Always make sure to construct SafeValue objects as
// close as possible to the input data so
// that it's easier to check if the value is safe.
this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
this.videoUrl =
this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
}
Live Demo:
It is just a code snippet explaining a particular concept and may not have any output
See the Pen jRQwQw by w3resource (@w3resource) on CodePen.
HTTP-level vulnerabilities
Angular has built-in support to help prevent two common HTTP vulnerabilities, cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). Both of these must be mitigated primarily on the server side, but Angular provides helpers to make integration on the client side easier.
Cross-site request forgery
In a cross-site request forgery (CSRF or XSRF), an attacker tricks the user into visiting a different web page (such as evil.com) with malignant code that secretly sends a malicious request to the application's web server (such as example-bank.com).
Assume the user is logged into the application at example-bank.com. The user opens an email and clicks a link to evil.com, which opens in a new tab.
The evil.com page immediately sends a malicious request to example-bank.com. Perhaps it's a request to transfer money from the user's account to the attacker's account. The browser automatically sends the example-bank.com cookies (including the authentication cookie) with this request.
If the example-bank.com server lacks XSRF protection, it can't tell the difference between a legitimate request from the application and the forged request from evil.com.
To prevent this, the application must ensure that a user request originates from the real application, not from a different site. The server and client must cooperate to thwart this attack.
In a common anti-XSRF technique, the application server sends a randomly generated authentication token in a cookie. The client code reads the cookie and adds a custom request header with the token in all subsequent requests. The server compares the received cookie value to the request header value and rejects the request if the values are missing or don't match.
This technique is effective because all browsers implement the same origin policy. Only code from the website on which cookies are set can read the cookies from that site and set custom headers on requests to that site. That means only your application can read this cookie token and set the custom header. The malicious code on evil.com can't.
Angular's HttpClient has built-in support for the client-side half of this technique. Read about it more in the HttpClient guide.
For information about CSRF at the Open Web Application Security Project (OWASP), see Cross-Site Request Forgery (CSRF) and Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet. The Stanford University paper Robust Defenses for Cross-Site Request Forgery is a rich source of detail.
Cross-site script inclusion (XSSI)
Cross-site script inclusion, also known as JSON vulnerability, can allow an attacker's website to read data from a JSON API. The attack works on older browsers by overriding native JavaScript object constructors, and then including an API URL using a <script> tag.
This attack is only successful if the returned JSON is executable as JavaScript. Servers can prevent an attack by prefixing all JSON responses to make them non-executable, by convention, using the well-known string ")]}',\n".
Angular's HttpClient library recognizes this convention and automatically strips the string ")]}',\n" from all responses before further parsing.
Auditing Angular applications
Angular applications must follow the same security principles as regular web applications and must be audited as such. Angular-specific APIs that should be audited in a security review, such as the bypassSecurityTrust methods, are marked in the documentation as security sensitive.
Previous: Reusable Animations
Next:
Route transition animations
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/angular/security.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics