Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 74 ยท Quality and Performance

Security and Accessibility

Keep Angular apps safe and usable - template sanitization, DomSanitizer pitfalls, XSRF protection, CSP, token storage, ARIA bindings, focus management and the CDK a11y tools.

Two kinds of quality are easy to postpone and expensive to retrofit: security and accessibility. A security hole lets an attacker run code in your users' browsers. An accessibility gap locks out people who use a keyboard, a screen reader or a high-contrast display. Angular helps with both, but only if you work with its defaults instead of around them.

This lesson covers the security side first (cross-site scripting, XSRF, Content Security Policy and where to keep tokens) and then accessibility (semantic HTML, ARIA bindings, focus management and the CDK's a11y tools).

Real versus stand-in. The typescript and html blocks are real Angular and read-only. The runnable examples are stand-ins: a deliberately small allowlist sanitizer and an XSRF header rule, written in plain TypeScript so you can see the logic. Angular's real sanitizer uses the browser's own HTML parser, and the stand-in below must never be used to protect a real application.

Cross-site scripting (XSS)

XSS happens when attacker-controlled text reaches the page as markup or script instead of as plain text. A comment containing <img src=x onerror=...> is harmless as text and dangerous as HTML.

Angular treats every value as untrusted by default. Interpolation ({{ comment() }}) writes text, so < becomes a literal character on the screen. Property bindings are checked against the security context of the target: HTML (innerHTML), style, URL (href, src) and resource URL (iframe src, script src).

HTML
<!-- text: always safe, markup is shown as characters -->
<p>{{ comment() }}</p>

<!-- HTML context: Angular sanitizes the string first -->
<div [innerHTML]="comment()"></div>

<!-- URL context: unsafe schemes such as javascript: are neutralized -->
<a [href]="profileUrl()">Profile</a>

For [innerHTML], Angular parses the string, removes elements and attributes that are not on its allowlist (scripts, event handler attributes, javascript: URLs) and keeps the harmless rest. In development it logs a warning when it changes something. Because the allowlist is maintained by the Angular team and run through the browser's parser, it is far more reliable than a regular expression.

flowchart LR
  U["Untrusted string"] --> B{"Binding type"}
  B -- "interpolation" --> T["Written as text<br/>(escaped by the DOM)"]
  B -- "innerHTML" --> S["Sanitizer removes<br/>unsafe tags and attributes"]
  B -- "href / src" --> V["URL checked,<br/>unsafe schemes neutralized"]
  B -- "iframe src, script src" --> R["Blocked unless explicitly trusted"]

Angular decides what to do from the binding's target, not from the string's content.

How a sanitizer thinks

A good sanitizer is an allowlist: only known-safe elements and attributes survive, and everything else is dropped. A blocklist ("remove <script>") always loses, because attackers find the tag or attribute you forgot. The stand-in below shows the idea with a tiny allowlist.

TypeScript A tiny allowlist sanitizer (a teaching stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice what the rules do. Unknown tags such as <img> disappear, <script> disappears with its content, all on... attributes are gone because only href on a link is ever copied, and unsafe URL schemes are rejected even when disguised with mixed case or a tab. That is the shape of the real thing, but a production sanitizer must also handle malformed markup, entities, namespaces and parser quirks, which is why you use the browser's parser and a maintained library instead of writing your own.

Bypassing the sanitizer, and why to avoid it

DomSanitizer offers methods such as bypassSecurityTrustHtml(), bypassSecurityTrustUrl() and bypassSecurityTrustResourceUrl(). They tell Angular "I vouch for this value", and Angular then skips the checks.

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

@Component({
  selector: 'app-note',
  template: `<div [innerHTML]="html()"></div>`,
})
export class NoteComponent {
  private sanitizer = inject(DomSanitizer);
  html = signal<SafeHtml>('');

  show(markupFromServer: string): void {
    // DANGEROUS if markupFromServer can contain user input
    this.html.set(this.sanitizer.bypassSecurityTrustHtml(markupFromServer));
  }
}

The pitfalls are all variations of one mistake: trusting something you did not write. Typical cases are rendering stored comments, markdown converted to HTML on the client, or a URL built from a query parameter. Prefer these alternatives, in order:

  1. Show the data as text with interpolation.
  2. Use [innerHTML] without bypassing, so Angular sanitizes it.
  3. Sanitize on the server with a library built for the job, then treat the output as trusted only if the pipeline is yours end to end.
  4. Bypass only for values you generate yourself, such as a fixed SVG from your own code, and never from user input.

Two more rules: never build templates from strings at runtime, and never concatenate user input into a template or into eval-like code. With the default AOT build, templates are compiled ahead of time and cannot be injected.

XSRF protection

Cross-site request forgery tricks a logged-in browser into sending a request you did not intend, because browsers attach cookies automatically. The classic defense is a token the attacker's page cannot read. Angular's HttpClient supports the common double-submit cookie scheme: the server sets a cookie named XSRF-TOKEN; JavaScript on your own origin reads it and copies it into an X-XSRF-TOKEN header; the server checks that header matches. A foreign site can make the browser send the cookie, but it cannot read it, so it cannot produce the header.

TypeScript
import { provideHttpClient, withXsrfConfiguration } from '@angular/common/http';

export const appConfig = {
  providers: [
    provideHttpClient(
      withXsrfConfiguration({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }),
    ),
  ],
};

The built-in behavior applies to mutating requests (not GET or HEAD) sent to relative URLs, and it does not overwrite a header you already set. Absolute URLs to other origins never get the token, which prevents leaking it. Your server must set the cookie and verify the header. The stand-in below models the client-side rule and a server check.

TypeScript The XSRF header rule and a server check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If your API uses a bearer token in the Authorization header instead of cookies, XSRF does not apply, because the browser does not attach that header by itself.

CSP and token storage

A Content Security Policy is a response header that tells the browser which scripts and styles may run. A strict policy turns many XSS bugs into blocked requests. Angular works with strict policies: avoid inline event handlers, and if you use a nonce-based policy, put your nonce on the root element with the ngCspNonce attribute so Angular can add it to the style tags it generates.

HTML
<app-root ngCspNonce="PER-REQUEST-RANDOM-VALUE"></app-root>

The nonce must be generated per response on the server. A fixed value in a static index.html gives no protection. Static hosting can use a hash-based policy instead.

Where to keep tokens. Anything in localStorage or sessionStorage is readable by any script on the page, so one XSS bug exposes it. A session cookie marked HttpOnly, Secure and SameSite cannot be read by JavaScript at all, which is why many teams prefer cookie sessions (plus XSRF protection) for browser apps. If you must hold an access token in memory, keep it short-lived and out of storage. Also remember that client-side checks are not security: route guards (Guards, Resolvers and Router Events) only shape the UI. The server must enforce every rule.

Accessibility

Accessibility starts with HTML, not with Angular. A <button> is focusable, activates with Enter and Space, and announces itself as a button. A <div (click)="save()"> does none of that.

HTML
<!-- Avoid -->
<div class="btn" (click)="save()">Save</div>

<!-- Prefer -->
<button type="button" (click)="save()">Save</button>

Use landmarks (<header>, <nav>, <main>), real headings in order, <label for> for every field and meaningful alt text. Reach for ARIA only when no native element fits. ARIA states change at runtime, so bind them. Use the attr. prefix, because many ARIA names are attributes, not DOM properties (Property, Attribute, Class and Style Binding):

HTML
<button
  type="button"
  [attr.aria-expanded]="open()"
  [attr.aria-controls]="'panel-1'"
  (click)="open.set(!open())">
  Details
</button>
<section id="panel-1" [hidden]="!open()">...</section>

Focus management

In a single-page app the browser does not move focus when the route changes, so a screen reader user may hear nothing. After navigation, move focus to the new page's heading or main region, and after closing a dialog, return focus to the control that opened it. The CDK helps here.

TypeScript
import { Component, ElementRef, inject, viewChild } from '@angular/core';
import { Router, NavigationEnd, RouterOutlet } from '@angular/router';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { filter } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-shell',
  template: `<main #main tabindex="-1"><router-outlet /></main>`,
  imports: [RouterOutlet],
})
export class ShellComponent {
  private main = viewChild.required<ElementRef<HTMLElement>>('main');
  private announcer = inject(LiveAnnouncer);

  constructor() {
    inject(Router).events
      .pipe(filter(e => e instanceof NavigationEnd), takeUntilDestroyed())
      .subscribe(() => {
        this.main().nativeElement.focus();
        this.announcer.announce('Page loaded');
      });
  }
}

tabindex="-1" makes the element focusable by script without adding it to the Tab order. The @angular/cdk/a11y package also provides cdkTrapFocus (keep Tab inside a dialog), FocusMonitor (tell keyboard focus from mouse focus) and ListKeyManager (arrow-key navigation for menus and lists). Angular Material components use these internally (Angular Material and the CDK).

Finally, test: tab through every page with the keyboard, zoom to 200 percent, check contrast, and run an automated checker such as axe or Lighthouse. Automated tools find only part of the problems, so keyboard testing remains essential.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Angular do with a string bound to [innerHTML]?

    [innerHTML] is the HTML security context. Angular parses the string, drops anything not on its allowlist (scripts, event handler attributes, javascript: URLs) and keeps the rest.
  2. 2. Which use of DomSanitizer is the most dangerous?

    Bypassing tells Angular to skip its checks. If the input can contain attacker-controlled markup, you have created an XSS hole yourself.
  3. 3. How does the double-submit XSRF defense stop a forged request from another site?

    The forged request carries the cookie automatically, but only scripts on your own origin can read it and set the X-XSRF-TOKEN header the server compares.
  4. 4. Why are access tokens in localStorage risky?

    One XSS bug is enough to read and steal everything in localStorage. HttpOnly cookies are invisible to JavaScript.
  5. 5. Why bind [attr.aria-expanded] instead of [aria-expanded]?

    Angular's square brackets target DOM properties by default. The attr. prefix sets the attribute directly, which is what assistive technology reads.

Summary

  • Angular treats values as untrusted: interpolation is text, and innerHTML, style, href and resource URLs are checked by security context.
  • A sanitizer is an allowlist run through the browser's parser. Do not write your own and avoid bypassSecurityTrust* for anything user-controlled.
  • HttpClient supports double-submit XSRF protection for mutating requests to relative URLs; the server must verify the header.
  • Use a strict CSP with a per-response nonce (ngCspNonce), keep tokens out of script-readable storage where you can, and enforce rules on the server.
  • Start accessibility with native elements, bind ARIA with attr., manage focus after navigation and dialogs, and use the CDK a11y tools plus real keyboard testing.

Next: Internationalization and Localization.