Top 5 Best Practices for Angular App Security | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Angular App Security

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

Tags:

Share this post:

Comments (8)

Useful blog content Jaganprakash ?

Thank you Balasubramanian S

Thanks it is very usefull.

Thank you Suman

Nice read

Thank you Antish Gajwani

Good post. Thanks.

Is sanitizing the app-root here is demonstration purpose or do you think it’s increasing the security.
We use DomSanitizer only if we need a cross site read in some particular part of the project.

Yes absolutely. Here i have added it for the demo purpose. But generally we use it whenever we use cross site url.

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed