Copied RSS Feed

Angular

Top 5 Best Practices for Angular App Security

Angular 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)

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 by 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.

Syncfusion Angular components are:

  • Lightweight
  • Modular
  • High-performing

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.

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 <h1> 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.

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.

bypassSecurityTrustHtmlThe 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.

Find the right property to fit your requirement by exploring the complete documentation for Syncfusion’s Angular components.

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 <script> 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 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, 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.

Be amazed exploring what kind of application you can develop using Syncfusion Angular components.

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 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, such as a Data Grid, Charts, and 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 the comments. You can also contact us through our support forumsupport portal, or feedback portal.

Reference

Please refer to the Angular Security Guide for more information.

Recommended resources

Meet the Author

Jaganprakash Vasudevan

Jaganprakash works as a product manager at Syncfusion. He has been working in .NET platforms, especially in web technology, for more than five years. He provides technical guidance and solutions for web-based projects.