Blog>
Snippets

Implementing Content Security Policy (CSP) in Angular

Set up a Content Security Policy in the Angular application using meta tags to prevent XSS attacks.
import { BrowserModule, DomSanitizer } from '@angular/platform-browser';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<h1>Welcome to our App!</h1>`
})
export class AppComponent implements OnInit {
  constructor(private domSanitizer: DomSanitizer, private browserModule: BrowserModule) { }

  ngOnInit(): void {
    const csp = `default-src 'self'; script-src 'self'; object-src 'none'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;`;
    const cspMeta = document.createElement('meta');
    cspMeta.httpEquiv = 'Content-Security-Policy';
    cspMeta.content = csp;
    document.head.appendChild(cspMeta);
  }
}
This Angular component sets up a Content Security Policy using meta tags upon initialization. The CSP restricts sources for scripts, styles, and fonts to specific trusted domains and prevents loading of any browser plugins, thereby mitigating the risk of XSS attacks. It uses Angular's DomSanitizer and BrowserModule to safely add a CSP meta tag to the document head during the component's ngOnInit lifecycle hook.