Top 5 Best Practices for Angular App Security
Tags: angular, productivity, security, webdev
Published: 2019-11-13 12:40:06

---
title: Top 5 Best Practices for Angular App Security
published: true
date: 2019-11-12 11:00:33 UTC
tags: angular, productivity, security, webdev
canonical_url: https://www.syncfusion.com/blogs/post/top-5-best-practices-angular-app-security.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2019/10/blog_1x-1.jpg
---

[Angular](https://angular.io/) is one of the most popular JavaScript platforms, widely used by developers around the world to develop web applications. These web applications have proven to be vulnerable to attacks from different sources, though, and it is our responsibility to safeguard our data. This article will help you develop a secure Angular application. The following are the best practices recommended to avoid vulnerabilities in your application:

- Prevent cross-site scripting (XSS)
- Block HTTP-related vulnerabilities
- Avoid risky Angular APIs
- Don’t customize Angular files
- Stay updated with the latest Angular library

## Prevent cross-site scripting (XSS)

Anybody can inject their scripts into DOM elements to steal our website data, such as credentials or web tokens. There are so many ways that attackers can inject their scripts; an easy way to do this is adding a _<script>_ tag. They might insert pop-ups or text fields to get user information. Another dangerous malfunction they might perform is to insert _<a>_ tags, which, if a user clicks them, will redirect the user to some other website.

To prevent these kinds of malicious activities, any values inserted into a webpage should be sanitized. Angular considers all the values as untrusted, by default. So, it is our responsibility to filter them before they’re added.

### Sanitization

This is the process of validating untrusted values, and it depends on context. The security contexts are HTML (binding inner HTML), style (CSS), attributes (binding values), and resources (referring files). We should covert the untrusted values provided by users into trusted values with _DomSanitizer_. For example, the following.

```js
import { Component, OnInit } from '@angular/core';
import { SecurityService } from './data.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
  selector: 'app-root',
  template: `<div [innerHtml] = "safeValue"></div>`,
  providers: [SecurityService]
})
export class AppComponent implements OnInit {
  safeValue: SafeHtml;
  constructor(private secure: SecurityService) {
    this.safeValue = this.secure.getSafeHtml("<h1>Sanitization Success</h1>");
  }
  ngOnInit() {
  }
}
```

We have to add a &lt;h1&gt; tag inside the div and bind **_safeValue_** to the **_innerHtml_** attribute. It is recommended to use attribute binding for sanitization. So, we pass the HTML string to our service method to get a secured value.

The following is the service code, and we have used _DomSanitizer’s_ API **_bypassSecurityHtml_** to sanitize the value.

```js
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';
 
@Injectable()
export class SecurityService {
constructor(private sanitizer: DomSanitizer) {
}
getSafeHtml(html: string) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
```

Eventually, the output of this sanitized HTML insertion will look like the following.

![Output of the sanitized HTML insertion.](https://www.syncfusion.com/blogs/wp-content/uploads/2019/10/Sanitization-Success.png)<figcaption>Output of the sanitized HTML insertion.</figcaption>

_bypassSecurityTrustHtml_The following methods are used for marking a value as trusted depending on the value type:

- _bypassSecurityTrustScript_
- _bypassSecurityTrustStyle_
- _bypassSecurityTrustUrl_
- _bypassSecurityTrustResourceUrl_

### Offline template compiler

Template injection is another form of inserting vulnerable scripts into our webpages. An offline template compiler helps us prevent an entire class and boosts the performance of the application, as well. Even though we can use dynamic templates in safer way, it is better to avoid those.

### Templates on server

Generating templates on a server is risky and makes a job easy for injectors, since the injection of templates from a server is similar to injection from other sites. Still, if you want to do so, you can use a templating language that prevents XSS vulnerabilities.

## Block HTTP-related vulnerabilities

There are two HTTP vulnerabilities that affect any Angular application: cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). But Angular has built-in helpers to prevent them at client-side itself.

### Cross-site request forgery

Third-party sites can redirect users to their own sites, which might send malicious requests to the application server. This technique is known as cross-site request forgery (CSRF or XSRF).

Let’s assume you are using a banking application and have clicked an advertisement link by mistake. This will open a new tab, and that site might request your banking server to transfer money to their account. If the application is not protected, you will lose your money.

To avoid such forgeries, applications must ensure the origin of any request, which requires both server-level and client-level security.

The most common and effective technique is sending an authentication token in a cookie using the server. 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. Since all browsers implement the same-origin policy, this approach is secured.

### Cross-site script inclusion (XSSI)

This is another way of stealing user information by including vulnerable scripts in our application. This is also known as JSON vulnerability. Attackers might include an API URL using a &lt;script&gt; tag to read application data. But this will only work if the JSON is executable. Angular’s HttpClient library recognizes this convention and automatically removes the string “)]}’,\n” from all responses before further parsing to make it non-executable.

## Avoid risky Angular APIs

Avoid Angular APIs marked in the documentation as “Security Risk.” The most common risky API we use is **_ElementRef_**. It permits direct access to the DOM and can make your application more vulnerable to XSS attacks. Review any use of [**_ElementRef_**](https://angular.io/api/core/ElementRef) in your code carefully. Use this API as a last resort when direct access to the DOM is needed. Use templating and data binding provided by Angular, instead. Alternatively, you can take a look at [**_Renderer2_**](https://angular.io/api/core/Renderer2), which provides an API that can safely be used even when direct access to native elements is not supported.

## Don’t customize Angular files

Customization of Angular files will make you rely on the version you are using. You might miss the security fixes in later versions. So, best practice is to share your improvements or fixes with the Angular community and make a pull request. Furthermore, your changes might override the existing behavior and lead to some security issues.

## Stay updated with latest Angular library

Angular regularly updates its libraries, and this may fix security defects discovered in previous versions. Check the Angular [_change log_](https://github.com/angular/angular/blob/master/CHANGELOG.md) for security-related updates. It’s best practice to upgrade your application with the latest version.

## Conclusion

In this blog post, we have discussed how to develop a secure Angular application and the best practices that are recommended to avoid vulnerabilities in your application.

Syncfusion provides [65+ Angular products](https://www.syncfusion.com/angular-ui-components/angular-calendar) such as a [Data Grid](https://www.syncfusion.com/angular-ui-components/angular-grid), [Charts](https://www.syncfusion.com/angular-ui-components/angular-charts), and [Scheduler](https://www.syncfusion.com/angular-ui-components/angular-scheduler). Take a moment to learn about our products and their numerous features.

Follow the practices outlined in this blog post and share your feedback in comments. You can also contact us through our [support forum](https://www.syncfusion.com/forums), [Direct-Trac](https://www.syncfusion.com/account/login), or [feedback portal](https://www.syncfusion.com/feedback/).

Reference: [https://angular.io/guide/security](https://angular.io/guide/security)

The post [Top 5 Best Practices for Angular App Security](https://www.syncfusion.com/blogs/post/top-5-best-practices-angular-app-security.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).