What is Angular?
Angular is one type of framework that is used for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript.
Nowadays, Angular is the most preferable front-end framework. Mostly, it is used in developing web apps. To better understand angular, one must have knowledge about how browser work and the security of angular projects. Web Security is also important to protect a site from security attacks and data theft. Now, we talk about some important practices which help us avoid security vulnerabilities in our Angular project/application.
This blog will help you to understand how to build security into your feature development and become a better developer by gaining a higher understanding of the security concepts that are relevant for Angular developers.
Now, we discuss some way for provide security to our angular application/project.
Prevent cross-site scripting (XSS)
In this way, the process will send a script to both attacker and user at the same time and prevent the user from accepting the script into a trusted website.
If the website is trusted, when users open the website that malicious script also executes. Also, they insert pop-ups or text fields to get user-sensitive information. Another way is to insert a tags, in which, when a user clicks them, the user will redirect to some other website.
To prevent these kinds of malicious activities, we have to sanitize all values which are inserted into a web page. by default, Angular considers all the values as untrusted. So, before they’re added we have to filter them.
Sanitization
This process is basically validating untrusted values, and it depends on context. The security contexts like HTML (binding inner HTML), attributes (binding values), style (CSS), and resources (referring files). using DomSenitizer We can convert the untrusted values into trusted values which are provided by the user. 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: `’, providers: [SecurityService] }) export class AppComponent implements OnInit { safeValue: SafeHtml; constructor(private secure: SecurityService) { this.safeValue = this.secure.getSafeHtml("Sanitization Success
"); } ngOnInit() { } }
We have to add a h1 tag inside the div and bind safeValue to the innerHtml attribute. It is use attribute binding for sanitization. So, for getting a secured value, we have to pass the HTML string into our service method.
The following below code is service file, and we have use value of the DomSanitizer API bypassSecurityHtml to sanitize the value.
Service file code:
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); } }
For making a value as trusted depending on the value type the following methods are used:
-
bypassSecurityTrustScript
-
bypassSecurityTrustStyle
-
bypassSecurityTrustUrl
-
bypassSecurityTrustResourceUr
Read More: Creating Reusable Angular Components
HTTP-related Vulnerabilities
The common HTTP vulnerabilities which may affect any angular application are cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). also, the angular framework has in-build assistants which can prevent them from the client-side.
now, we will check how to prevent these threats from damaging the application.
cross-site request forgery (CSRF or XSRF)
In this type of vulnerability, the attacker stays as a hidden mediator. This process is done by the user. Attackers make HTTP requests to the server with help of any authorized user of that site. An attacker can redirect users to their own sites, which is send malicious requests to the application server.
Now see it working with an example, first, an authenticated user is login into his/her website then the attacker will try to make an HTTP request by the user by clicking some links unfamiliar link and the attacker can access secret information from that request. Another example is if you transfer money using a banking application and you see an advertisement link and click it then it will migrate you to a new tab, and it will send a request to your banking application server to transfer money to their account so, your money will be lost from your bank account. If this user is administrative, all information is accessible by the attacker, which can be accessed by that administrative user.
To avoid such a type of attack, applications must ensure request, which requires both server-level and client-level security.
To avoid these types of attacks, we use the most common and effective technique to send an authentication token in a cookie using the server. Now when the request will send then the HTTP request server will compare token data from the cookie and prevent access data if the token is not authorized.
Cross-site script inclusion (XSSI)
Attackers are using unprotected scripts for this method. so avoid any third-party script which is coming from an untrusted domain, because if it is not secure. The attacker can add executable code into the script and when the user executes this script in our domain we might compromise any essential information.
Another way Attackers can add an API URL using a script tag. This is also known as JSON vulnerability. Angular has HttpClient library that can help programmers to fetch this type of convention and automatically remove the string “)]}’,\n” from all codes and make it non-executable.
Avoid Hazardous Angular API Endpoints
Avoid angular APIs which are marked as “Security Risk” in the documentation. The most common security risky API we use is ElementRef.
The ElementRef API provides instant access to attackers into the DOM in your pages making the applications vulnerable to XSS attacks. This Angular API should be used when there is direct DOM access is necessary. In short review any use of ElementRef in your code carefully. Use templating and data binding provided by Angular also you can use Renderer2 API, which can be safely be used even when direct access to native elements is not supported.
Use Route Guards on the Navigation
First of all, we can accept or decline permission to navigate the URL requested by users by working on the route guard interface. Route guards are using a boolean value concept like if they all return true value then the user can navigate to the requested URL and if anyone returns a false value then the user will be a block to navigate that URL
Different types of route guards:
-
CanActivate:Checks for the component can be accessed by the user or not
-
CanActivateChild:This method checks whether the child component can be accessed or not
-
CanLoad:It can be checked before the load feature module
-
Resolve:It makes sure that data related navigation is available or not so it is pre-fetch the route data.
-
CanDeactivate: It asks for authorization to discard the changes
Route Guard example:
import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; export class RouteGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // user may login if token exists if (localStorage.getItem('token')) { return true; } // otherwise redirect to login page this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; } }
Now, apply the same route guard in the route of the RouteModule. Following code, we have defined the route app.module file.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouteGuard } from './Services/routeGuard'; .... @NgModule({ declarations: [ .... ], imports: [ RouterModule.forRoot([ { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [RouteGuard] }, { path: 'myprofile', component: MyProfileComponent, canActivate: [RouteGuard] }, .... ]), .... ], ....}) export class AppModule { }
Generally, user logged-in information like name, email, authentication token, etc will be used by the programmer. we store information in local storage or window session storage.
Here, Windows session storage is more secure than local storage because it is removing user data when the browser gets close and it will prevent any unauthorized users from accessing the user’s data.
Use window session storage or local storage to maintain data according to your project requirement but make sure that when the user logged out the data of that user must be cleared.
Planning to Hire dedicated Angular Developer ?
Your Search ends here.
Avoid customizing Angular files
In the software world user always want to make customization, but customization in Angular libraries is the worst idea.
By doing customization, you can stay on one particular Angular version; after customizing the library, there is no way for you to apply patches or update the old to the latest version without risk the functionality of your application.
If you are modifying any files of the Angular core module, then this may affect the security and you have to face some security issues. Any unknown modification or change in the default content of an angular can change the default behavior of the current version also harm the existing functionality.
So, if you want to essentially change or fix any existing problem by making requests, you should let the Angular community know about your customization and they will update your changes if it does not affect any of the current features.
Stay updated with the latest Angular library
One of the most integral parts of the software world is to give the latest advancements and innovations. Angular is regularly updated its libraries day-by-day to enrich existing functionality and providing better performance. Users will find the latest improved version in the market time-to-time, with stability and functions that will make the development much easier for the professionals.
Angular continuously updates its library so, it can fix security defects that are discovered in the previous versions. So, keep updating your angular library to take maximum advantage of the angular framework to keep your system flexible. Go through the Angular change log for security-related updates.
Conclusion
In this blog, we have learned what is the importance of security in our angular application. Also, we have learned various ways in which we can secure our angular application.
The Complete Guide To Angular Security Table of Content 1. What is Angular? 2. Prevent cross-site scripting (XSS) 2.1. Sanitization 3. HTTP-related Vulnerabilities 3.1. cross-site request forgery (CSRF or XSRF) 3.2. Cross-site script inclusion (XSSI) 4. Avoid Hazardous Angular API Endpoints 5. Use Route Guards on the Navigation 6. Avoid customizing Angular files 7. Stay updated with the latest Angular library 8. Conclusion What is Angular? Angular is one type of framework that is used for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. Nowadays, Angular is the most preferable front-end framework. Mostly, it is used in developing web apps. To better understand angular, one must have knowledge about how browser work and the security of angular projects. Web Security is also important to protect a site from security attacks and data theft. Now, we talk about some important practices which help us avoid security vulnerabilities in our Angular project/application. This blog will help you to understand how to build security into your feature development and become a better developer by gaining a higher understanding of the security concepts that are relevant for Angular developers. Now, we discuss some way for provide security to our angular application/project. Prevent cross-site scripting (XSS) In this way, the process will send a script to both attacker and user at the same time and prevent the user from accepting the script into a trusted website. If the website is trusted, when users open the website that malicious script also executes. Also, they insert pop-ups or text fields to get user-sensitive information. Another way is to insert a tags, in which, when a user clicks them, the user will redirect to some other website. To prevent these kinds of malicious activities, we have to sanitize all values which are inserted into a web page. by default, Angular considers all the values as untrusted. So, before they’re added we have to filter them. Sanitization This process is basically validating untrusted values, and it depends on context. The security contexts like HTML (binding inner HTML), attributes (binding values), style (CSS), and resources (referring files). using DomSenitizer We can convert the untrusted values into trusted values which are provided by the user. 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: ` ’, providers: [SecurityService] }) export class AppComponent implements OnInit { safeValue: SafeHtml; constructor(private secure: SecurityService) { this.safeValue = this.secure.getSafeHtml(" Sanitization Success"); } ngOnInit() { } } We have to add a h1 tag inside the div and bind safeValue to the innerHtml attribute. It is use attribute binding for sanitization. So, for getting a secured value, we have to pass the HTML string into our service method. The following below code is service file, and we have use value of the DomSanitizer API bypassSecurityHtml to sanitize the value. Service file code: 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); } } For making a value as trusted depending on the value type the following methods are used: bypassSecurityTrustScript bypassSecurityTrustStyle bypassSecurityTrustUrl bypassSecurityTrustResourceUr Read More: Creating Reusable Angular Components HTTP-related Vulnerabilities The common HTTP vulnerabilities which may affect any angular application are cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). also, the angular framework has in-build assistants which can prevent them from the client-side. now, we will check how to prevent these threats from damaging the application. cross-site request forgery (CSRF or XSRF) In this type of vulnerability, the attacker stays as a hidden mediator. This process is done by the user. Attackers make HTTP requests to the server with help of any authorized user of that site. An attacker can redirect users to their own sites, which is send malicious requests to the application server. Now see it working with an example, first, an authenticated user is login into his/her website then the attacker will try to make an HTTP request by the user by clicking some links unfamiliar link and the attacker can access secret information from that request. Another example is if you transfer money using a banking application and you see an advertisement link and click it then it will migrate you to a new tab, and it will send a request to your banking application server to transfer money to their account so, your money will be lost from your bank account. If this user is administrative, all information is accessible by the attacker, which can be accessed by that administrative user. To avoid such a type of attack, applications must ensure request, which requires both server-level and client-level security. To avoid these types of attacks, we use the most common and effective technique to send an authentication token in a cookie using the server. Now when the request will send then the HTTP request server will compare token data from the cookie and prevent access data if the token is not authorized. Cross-site script inclusion (XSSI) Attackers are using unprotected scripts for this method. so avoid any third-party script which is coming from an untrusted domain, because if it is not secure. The attacker can add executable code into the script and when the user executes this script in our domain we might compromise any essential information. Another way Attackers can add an API URL using a script tag. This is also known as JSON vulnerability. Angular has HttpClient library that can help programmers to fetch this type of convention and automatically remove the string “)]}’,\n” from all codes and make it non-executable. Avoid Hazardous Angular API Endpoints Avoid angular APIs which are marked as “Security Risk” in the documentation. The most common security risky API we use is ElementRef. The ElementRef API provides instant access to attackers into the DOM in your pages making the applications vulnerable to XSS attacks. This Angular API should be used when there is direct DOM access is necessary. In short review any use of ElementRef in your code carefully. Use templating and data binding provided by Angular also you can use Renderer2 API, which can be safely be used even when direct access to native elements is not supported. Use Route Guards on the Navigation First of all, we can accept or decline permission to navigate the URL requested by users by working on the route guard interface. Route guards are using a boolean value concept like if they all return true value then the user can navigate to the requested URL and if anyone returns a false value then the user will be a block to navigate that URL Different types of route guards: CanActivate:Checks for the component can be accessed by the user or not CanActivateChild:This method checks whether the child component can be accessed or not CanLoad:It can be checked before the load feature module Resolve:It makes sure that data related navigation is available or not so it is pre-fetch the route data. CanDeactivate: It asks for authorization to discard the changes Route Guard example: import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; export class RouteGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // user may login if token exists if (localStorage.getItem('token')) { return true; } // otherwise redirect to login page this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; } } Now, apply the same route guard in the route of the RouteModule. Following code, we have defined the route app.module file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouteGuard } from './Services/routeGuard'; .... @NgModule({ declarations: [ .... ], imports: [ RouterModule.forRoot([ { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [RouteGuard] }, { path: 'myprofile', component: MyProfileComponent, canActivate: [RouteGuard] }, .... ]), .... ], ....}) export class AppModule { } Generally, user logged-in information like name, email, authentication token, etc will be used by the programmer. we store information in local storage or window session storage. Here, Windows session storage is more secure than local storage because it is removing user data when the browser gets close and it will prevent any unauthorized users from accessing the user’s data. Use window session storage or local storage to maintain data according to your project requirement but make sure that when the user logged out the data of that user must be cleared. Planning to Hire dedicated Angular Developer ? Your Search ends here. See here Avoid customizing Angular files In the software world user always want to make customization, but customization in Angular libraries is the worst idea. By doing customization, you can stay on one particular Angular version; after customizing the library, there is no way for you to apply patches or update the old to the latest version without risk the functionality of your application. If you are modifying any files of the Angular core module, then this may affect the security and you have to face some security issues. Any unknown modification or change in the default content of an angular can change the default behavior of the current version also harm the existing functionality. So, if you want to essentially change or fix any existing problem by making requests, you should let the Angular community know about your customization and they will update your changes if it does not affect any of the current features. Stay updated with the latest Angular library One of the most integral parts of the software world is to give the latest advancements and innovations. Angular is regularly updated its libraries day-by-day to enrich existing functionality and providing better performance. Users will find the latest improved version in the market time-to-time, with stability and functions that will make the development much easier for the professionals. Angular continuously updates its library so, it can fix security defects that are discovered in the previous versions. So, keep updating your angular library to take maximum advantage of the angular framework to keep your system flexible. Go through the Angular change log for security-related updates. Conclusion In this blog, we have learned what is the importance of security in our angular application. Also, we have learned various ways in which we can secure our angular application.
Build Your Agile Team