Security in Angular

Pravin M
4 min readDec 25, 2023
Security in Angular

Source: Security in Angular

For more questions and answers visit our website at Frontend Interview Questions

Angular provides several security features and best practices to help developers build secure web applications. Here are some of the key security features in Angular, along with examples:

  1. Template Sanitization:

Angular automatically sanitizes user-provided inputs in templates to prevent Cross-Site Scripting (XSS) attacks. For example, consider the following template:


{{ user.name }}

If the `user.name` property contains potentially harmful HTML code, Angular automatically sanitizes it and renders it as plain text, preventing any script execution.

->We have to add code to sanitize untrusted values, 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


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);
}
}

The following methods are used for marking a value as trusted depending on the value type:

bypassSecurityTrustScript
bypassSecurityTrustStyle
bypassSecurityTrustUrl
bypassSecurityTrustResourceUrl

2. Cross-Site Scripting (XSS) Protection: Angular automatically escapes interpolated values and data bindings by default to prevent XSS attacks. For example, consider the following template:


{{ user.bio }}

If the `user.bio` property contains a script tag or any other HTML code, Angular escapes the characters and renders it as plain text, preventing script execution.

3. Content Security Policy (CSP) Support:

Angular allows you to enforce a strict Content Security Policy for your application. This helps protect against XSS attacks by defining the sources from which the application can load resources. For example, you can configure a CSP in the HTML header as follows:


<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com;">

This example restricts the loading of scripts to the same origin and a trusted CDN.

4. HTTP Interceptors:

Angular’s HttpClient module provides interceptors that allow you to modify HTTP requests and responses. You can use interceptors to implement security-related features, such as adding authentication headers or handling CSRF tokens. For example, you can create an interceptor to add an authentication token to every outgoing request:


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const token = 'your-auth-token';
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(authReq);
}
}

This interceptor adds an `Authorization` header with a bearer token to each outgoing HTTP request.

5. Authentication and Authorization:

Angular provides a flexible framework for implementing authentication and authorization mechanisms. You can leverage features like route guards, authentication services, and token-based authentication (e.g., JWT) to secure routes and control access to protected resources. Here’s an example of a route guard that restricts access to a specific route:


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

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}

canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable | Promise | boolean | UrlTree {
// Check if user is authenticated, e.g., by verifying the presence of a valid token
const isAuthenticated = ...;

if (isAuthenticated) {
return true;
} else {
// Redirect to login page or show access denied message
this.router.navigate(['/login']);
return false;
}
}
}

This guard checks if the user is authenticated and allows or denies access to the protected route accordingly.

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

These are just a few examples of the security features provided by Angular. It’s important to implement additional security measures based on your application’s requirements, such as input validation, secure communication protocols (HTTPS), proper error handling, and regular security updates for dependencies and libraries used in the application.

--

--

Pravin M

I am a frontend developer with 10+ years of experience