Tips to Secure Your Angular Application

The global influx of digital transformation is creating pressure on infrastructure. All the while, threat actors are continually improving their attack techniques. If there is a vulnerability to be found, it will be exploited. This is why many teams are shifting security to the left, even going as far as evolving their dev methodology from DevOps to DevSecOps.

There are still remaining concerns, most of which focus on release time. However, you do not have to compromise fast releases in favor of security. It doesn’t have to be a question of either/or.

In this article, you will learn about four methods you can use to secure your Angular apps. These are simple security practices that should not interrupt your workflow.

Angular Overview

Angular is a framework that allows you to build single-page applications (SPA) using TypeScript, an open-source language developed by Microsoft, which is a strict superset of JavaScript. Angular provides several TypeScript libraries with its core functionality and lets you add more libraries for additional, optional features.

Angular applications are built using NgModules. Modules provide a compilation context for components. An Angular application must have at least one root module, and may have many more feature modules.

The Angular architecture is built around components, views, and services:

  1. Components define views—screen elements that you can choose to display to the user and modify according to application logic.
  2. Components use services—service providers are added to modules using dependency injection, making Angular modules modular and easy to reuse.
  3. Both components and services are classes, with decorators that include metadata, which tells the Angular framework how they should be used.

Angular vs AngularJS: Key Differences

In 2010, Google first released AngularJS, also called Angular 1, and it was hugely popular. However, it faced tough competition from React and Vue.

In 2014, Google announced a complete rewrite of AngularJS, shifting it from JavaScript to TypeScript. The advantage of TypeScript was that it offered some static typing features. They named the new version Angular 2.

All Angular versions, from 2 onwards, are known as “Angular” or “Angular 2+.” For a versioning history of Angular, here is a complete Angular roadmap.

Angular 2 was a complete change for Angular users—the programming language, the architecture, and the approach to data all changed. Today Angular 2+ based on TypeScript is at version 9, and AngularJS continues to be used by many developers as a legacy framework.

Security considerations when using AngularJS

  1. AngularJS is less actively maintained than Angular 2+. Older versions of AngularJS (before 1.7) have 29 known software vulnerabilities, as reported by Snyk, including prototype pollution, Distributed Denial of Service (DDoS), cross-site scripting (XSS), and arbitrary command execution.
  2. Review these vulnerabilities, assess the risks to your project and if at all possible, upgrade AngularJS to the latest version.
  3. Note that AngularJS 1.7 will only be maintained until its end of life in June 2021.

The rest of our discussion will focus on the newer Angular 2+ or just “Angular.”

4 Ways to Secure Your Angular App

Review the following best practices to learn how to secure applications running on Angular 2 and higher. These best practices will help you prevent attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF), which can be a low-profile automated attack but may also be part of an advanced persistent threat, used as the first step in a larger attack campaign.

1. Prevent Cross-Site Scripting (XSS)

An XSS attack involves attackers inserting scripts into a DOM element on your packages to perform malicious actions such as stealing user data. To prevent this, you need to sanitize untrusted inputs in several places:

  1. HTML (binding inner HTML)
  2. Style (CSS)
  3. Attributes (binding values)
  4. Resources (referring files)

Always convert untrusted values, provided by an external user, into trusted values using DomSanitizer. Bind safeValue to the innerHtml attribute, passing the HTML string to the service method to get a secured value.

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

2. Don’t Customize Angular Files

As tempting as it may be to customize Angular libraries to fit your needs, doing so will make you reliant on the current version of Angular that you're using. You will find it difficult to upgrade to later versions of Angular and may miss out on critical security fixes and features. The best way to make improvements and fixes to Angular libraries is to share your changes with the community via a pull request. This will allow other developers to review your changes and consider adding them to the next version of Angular.

3. Avoid Risky Angular API Endpoints

Some Angular APIs are marked in the documentation as a security risk, most commonly ElementRef. This API grants attackers direct access to the DOM on your pages and makes your apps vulnerable to XSS. Only use this API if you have no other choice, and when direct DOM access is absolutely required.

Instead of ElementRef, it is recommended that you use the templating or data binding capabilities provided natively in Angular. You can also use the Renderer2 API, which is safer than using ElementRef.

4. HTTP-Level Vulnerabilities

Use Angular’s built-in features to prevent cross-site request forgery (CSRF) and cross-site script inclusion (XSSI). While these are security issues that need to be addressed on the server-side, Angular’s HttpClient provides helpers to integrate your application with a server that is resistant to these attacks.

Cross-Site Request Forgery (CSRF):

CSRF is an attack where a user trusted by an application sends unauthorized, malicious commands. A common way to mitigate it is to have the application server send a random authentication token, included in a cookie. The client reads the cookie, and in all subsequent requests, adds a custom request header with the same token. This makes it possible to reject a request made by an attacker, who does not possess the authentication token.

When you use Angular HttpClient, you get built-in support for authentication tokens on the client-side.

Cross-Site Script Inclusion (XSSI):

XSSI is an attack that allows an attacker’s website to read data from your application’s JSON API. It exploits a vulnerability on old browsers that enables overriding native JavaScript object constructors. It can then provide an API URL using a <script> tag.

The server can mitigate this attack by making all JSON responses non-executable. For example, this can be done by prefixing them with the string ")]}',\n". Angular’s HttpClient recognizes this convention and automatically strips the string ")]}',\n" from all JSON responses.

Additional Angular Performance Resources:

Angular Security - Conclusion

Security is a crucial concern that should be addressed not only by security professionals but also by developers. The simple practice of writing secure code can help prevent the exploitation of bugs and errors. Sure, there is no such thing as “perfect”, and there will always be fixes to make, patches to release, and urgent matters to respond to. However, you can adopt a secure code mindset, and avoid unnecessary risks.

Looking for framework-agnostic web components? GrapeCity has a complete set of JavaScript UI components and powerful Excel-like JavaScript spreadsheet components. We have deep support for Angular (as well as React and Vue) and are dedicated to extending our components for use in modern JavaScript frameworks.

Here's a look at several of our Angular demos.

Try Wijmo's JavaScript UI controls free for 30 days

Download the latest version of Wijmo

Download Now!

Try ComponentOne's UI controls

Download the latest version of ComponentOne Studio Enterprise

Download Now!