Angular Security

Angular Security

Web applications face constant threats from malicious attackers.

One of the most dangerous and common attacks is Cross-Site Scripting (XSS).

XSS occurs when an attacker tricks your application into executing malicious JavaScript code within a user's browser.


Built-in XSS Protection

Angular is designed to be highly secure right out of the box.

By default, Angular treats all values bound to the DOM (via string interpolation {{ }}) as untrusted.

Before rendering the data, Angular automatically escapes it, converting <script> tags into harmless text blocks!

Automatic Escaping:

export class SecureComponent {
  // An attacker tries to inject a malicious script
  maliciousData = '<script>alert("Your app is hacked!")</script>';
}

// In HTML: {{ maliciousData }} // Angular renders it safely as literal text, NOT executable code!


Trusting Safe Content (DomSanitizer)

Sometimes, your backend genuinely sends safe, pre-formatted HTML that you actually want to execute.

Because Angular's security is so strict, it will block it by default.

To bypass this, you must explicitly mark the HTML as safe by injecting the DomSanitizer service.

Bypassing Security Safely:

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

export class HtmlComponent { safeContent: SafeHtml;

constructor(private sanitizer: DomSanitizer) { const trustedString = '<b>I am trusted bold text</b>';

// Explicitly telling Angular to trust and render this specific HTML
this.safeContent = this.sanitizer.bypassSecurityTrustHtml(trustedString);

} }

Warning: Never use bypassSecurityTrustHtml on data provided directly by users!


Route Protection & JWTs

Security isn't just about preventing scripts; it's about protecting data.

To secure your application, you must lock down frontend routes using Route Guards (as covered previously).

Furthermore, every API request fetching sensitive data must include a JSON Web Token (JWT).

Angular handles this securely by attaching the token via HTTP Interceptors rather than storing it locally in easily accessible variables.


CSRF Protection

Cross-Site Request Forgery (CSRF) is an attack where a malicious site tricks your browser into executing actions on a site you are currently logged into.

Angular includes an HttpClientXsrfModule which mitigates this automatically!

It reads a specific token from a cookie and sets it as an HTTP header on every outgoing request.


Exercise 1 of 2

?

By default, what does Angular do when you bind data containing <script> tags into the HTML template?

Exercise 2 of 2

?

Which Angular service must you use to explicitly tell the framework to render raw HTML that you know is 100% safe?