×

Tips to Secure Your Angular Application

Jignesh Trivedi  Print   10 min read  
18 Feb 2022
 
Advanced
32.8K Views

Software security is a major concern for every application. There are some common vulnerabilities reported for web applications that we need to care for all the applications. In this article, I will discuss the vulnerabilities possible with the Angular application and how to prevent these vulnerabilities by using best practices.

Prevent an application from Cross-Site Scripting (XSS)

XSS allows attackers to inject client-side script or malicious code into web pages that can be viewed by other users. This kind of attack mostly happened via the query string, input field, request headers. For Preventing XSS attacks, we must present the user to enter malicious code from DOM. For example, an attacker might enter some script tag to input filed and that might render as read-only text.

By default, Angular treats all values as untrusted when the values are inserted into the DOM via the attribute, interpolation, properties, etc. It escapes and sanitizes values before rendering. The XSS-related security in Angular is defined in "BrowserModule". Angular's DomSanitizer helps to clean untrusted parts of the value. The DomSanitizer class looks as follows.

export declare abstract class DomSanitizer implements Sanitizer {
 abstract sanitize(context: SecurityContext, value: SafeValue | string | null): string | null;
 abstract bypassSecurityTrustHtml(value: string): SafeHtml;
 abstract bypassSecurityTrustStyle(value: string): SafeStyle;
 abstract bypassSecurityTrustScript(value: string): SafeScript;
 abstract bypassSecurityTrustUrl(value: string): SafeUrl;
 abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl;
}

Here, there are two type of method patterns: sanitize and bypassSecurityTrustX (bypassSecurityTrustHtml, bypassSecurityTrustStyle, etc.). The sanitize method gets untrusted value from the context and returns the trusted value. The bypassSecurityTrustX method gets untrusted values from the context and according to the value usage, it returns a trusted value. In specific conditions, we might require disabling sanitization. By setting up anyone bypassSecurityTrustX methods, We can bypass security and bind the value.

Example
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

@Component({
 selector: test-Component',
 template: `
 <div [innerHtml]="myHtml"></div>
 `,
})
export class App {
public myHtml: string;
 constructor(private sanitizer: DomSanitizer) {
 this. myHtml = sanitizer.bypassSecurityTrustHtml('<h1>Example: Dom Sanitizer: Trusted HTML </h1>') ;
 }
}

Be careful when turn-off or bypassing any security setting that might malicious code and we might inject security vulnerability into our application. Sanitization inspects all the untrusted values and converts them into a value that is safe to insert into the DOM tree. It does not change the value at all times and Angular allows some untrusted values for HTML, styles, and URLs. Angular defined some security contexts as follows.

  • It uses HTML context when interpreting a value as HTML

  • It uses Style context when any CSS bind into the style property

  • It uses URL context when binding URL (example<a href>)

    Angular generate the warning and prints it into the console when it changes the value during sanitization.

Use Route guards when required

The router guards are the interface that tells the weather route to request a URL or not. It makes a decision by interface return value i.e. if the interface returns true then it routes to the new URL else not. There are mainly five types of guards and all are called in a particular sequence. We can modify routing behavior depending on which guard is used.

We can create the route guard using the following CLI command.

ng new routing-app-example --routing --defaults

Following are the provided route guard

  • CanActivate: checks the route access

  • CanActivateChild: Checks the child route access

  • CanDeactivate: it asks permission to discard the changes

  • CanLoad: Checks before load feature module

  • Resolve: it pre-fetch the route data

    In the following example code, I have implemented a CanActivate route guard that allowed route if token data is available in local storage else redirect to the login page. In the route guards, we can put any kind of checking such as user roles has right to access page, etc.

Route Guard Example

 
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthorizationCheck implements CanActivate {

 constructor(private router: Router) { }

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
 //If token data exist, user may login to application
 if (localStorage.getItem('TokenInfo')) {
 return true;
 }

 // otherwise redirect to login page with the return url
 this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
 return false;
 }
}

We can apply this route guard to the route in RouteModule. Following the example code, I have defined the routing app.module file.

 
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
....
....
...
import { AuthorizationCheck } from './Services/authorizationCheck'
...
...
@NgModule({
 declarations: [
 ....
 ....
 ....
 ],
 imports: [
 ....
 ....
 RouterModule.forRoot([
 { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthorizationCheck] },
 { path: 'counter', component: CounterComponent, canActivate: [AuthorizationCheck] },
 ....
 ....
 ])
 ],
 ...
 ...
})
export class AppModule { }

In this way, we can protect our route, and this cannot be easily hackable. However, if the user has knowledge about the system then he/she can break the route guard.

You can refer full Authentication example here Token-based Authentication in Angular.

Remove Local storage and windows session storage data after logout from the application

After, successful login to the application, generally we store user data such as user name, authentication token, etc. to either local storage or windows session storage. This type of user information may use by the hacker/attacker and take access to applications if they are available after the user logout.

Local storage can be shared between multiple tabs as well as multiple browser sessions. Windows session storage can only be accessible to a particular browser session and it kills when the browser is closed. I recommended using windows session storage instead of local storage to store such information. But it is depending on the application requirement. So, it is best practice to remove such data from local storage and windows session storage after logout.

An angular route guard is a great tool that helps us to protect every route of the application. and it also helps us to implement custom route logic, get the data from the back-end platform, and so on. We can also create multiple route guards against a single route or use the same guard against multiple routes respectively.

Implement CSP (Content Security Policies)

It added a layer of security that helps us to detect and mitigate certain types of attacks (including data injection and XSS attacks). To enable Content Security Policy, our web server (API) must return the appropriate Content-Security-Policy HTTP header. We can implement CSP either by using the HTTP Meta tag or by defining "Content-Security-Policy" to the header.

<meta http-equiv="Content-Security-Policy" content="default-src https://myexample.com; child-src 'none'; object-src 'none'">

Or

Content-Security-Policy: script-src 'self' https://myexample.com

Do not use DOM’s APIs directly

Angular recommended using Angular templates rather than using DOM API such as document, ElementRef, etc. Angular does not have control over these DOM APIs, so it does not provide protection against security vulnerabilities and attackers can inject malicious code into the DOM tree.

Prevent CSRF (Cross-site request forgery)

It is also known as Session riding. Attacker copies forge as a trusted source and execute actions on user behalf. This kind of attack can damage both client relations and business. The common mechanism used by HttpClient to support CSRF attack protection. when the application made any HTTP request, the interceptor reads the information about the token from the cookies and sets the HTTP header. The interceptor sends application cookies on all requests such as POST etc. to the relative URL, but it does not send cookies with HEAD/GET requests and requests with absolute URLs.

So, the server needs to set a token in JavaScript readable session cookie on the first GET request or page load. With subsequent requests, the server verifies this token with request header cookies. In this way, the server can be sure that the code running on the same domain. This token must be unique for each user and verified by the server. CSRF protection also needs to apply to the server (our back-end service) as well. In angular applications, we can use different names for the XSRF token cookie or header. We can override the defaults value by using HttpClientXsrfModule.withOptions method.

imports: [
 HttpClientModule,
 HttpClientXsrfModule.withOptions({
 cookieName: 'my-Cookie',
 headerName: 'my-Header',
 }),
],

Prevent Cross-Site Script Inclusion (XSSI)

Cross-site script inclusion (CSSI) is also known as JSON vulnerability that allows the attacker to read data from JSON API. An attacker can override the native JavaScript object constructor and include an API URL using a script tag. The attacker may be getting success if returned JSON is executable as JavaScript.We can prevent an attack by prefixing all JSON responses with the well-known string ")]}', \n". This makes JSON non-executable. Angular library (HttpClient) recognizes the "\n" character and makes the script is not executable.

Up-to-date Angular Libraries

There are continuous updates provided for bug fixes, security patches, and feature enhancements at regular intervals, so it is recommended to update the Angular libraries. It is possible that security-related issues are fixed in newer releases that prevent any security vulnerabilities injected by attackers.

Avoid Modifying the Angular Copy

It is recommended to avoid Modifying the Angular Copy because it creates a hard link between our application and Angular libraries. As described in the above point, there are continuous updates provided for bug fixes, security patches, and feature enhancements in Angular libraries, so it is very difficult to upgrade to newer Angular versions.

Use Offline Template Compiler

It would be recommended to use an offline template compiler to prevent security vulnerabilities called template injection. It is recommended to use the offline template compiler in production deployment. Basically, Angular trusts on template code, so someone can add vulnerabilities to dynamically created templates as a result of a malicious attack on the DOM tree.

Validate user-submitted data on server-side code

It would be good practice to validate all the submitted data on server-side code. This can help to prevent data-related vulnerabilities. Sometimes, attackers can use the XSS method and try to inject malicious data into our application. If we validate the data at the server-side as well, we can prevent our application from this kind of attack.

Do not use components with Known Vulnerabilities

There are many third-party libraries components available and nowadays it is just impossible to develop the application without such libraries. These libraries may have known vulnerabilities that can be used by the attacker to inject malicious code or data into our application. These libraries can have security vulnerabilities such as CSRF, XSS, buffer overflows, etc.

Solution

  • Download the library from a trusted source

  • Always use an updated version of the library (it may fix some critical security defect in the latest version)

  • Monitor the library's Vulnerabilities from the source such as NVDhttps://nvd.nist.gov/vulnand CVE https://cve.mitre.org/

Summary

In this article, I have covered some of the top possible attacks on our Angular application and how to prevent our application from such an attack. Dot Net Tricks Angular 2 to 10 web API live interactive training aligned with real-time which is delivered by Google GDE and Microsoft MVP globally. The angular online training program helps you learn to build projects using web API ASP.NET  MVC5  and node.js.Thanks for reading.

Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Learn to Crack Your Technical Interview

Accept cookies & close this