Angular course Β· Module 12: Security and Performance
Security in Angular - Castle Fortifications
In this lesson5
Application security is like the walls of Himeji Castle ε - multi-layered defense against enemies. Himeji Castle survived for centuries thanks to its well-designed fortifications - your application needs the same level of protection!
Types of Threats
| Threat | Description | Angular Protection |
|---|---|---|
| XSS | Injection of malicious scripts | Automatic sanitization |
| CSRF | Cross-site request forgery | HttpXsrfModule |
| Injection | Code injection | Parameterized queries |
| Clickjacking | Hidden iframes | X-Frame-Options |
Protection Against XSS
Angular automatically sanitizes all values in templates:
@Component({
template: `
<!-- Safe - Angular escapes HTML -->
<div>{{ userInput }}</div>
<!-- Safe - Angular sanitizes URL -->
<a [href]="userUrl">Link</a>
<!-- Safe - Angular sanitizes styles -->
<div [style.background]="userBackground">...</div>
`
})
export class SafeComponent {
// Even if userInput = '<script>alert("XSS")</script>'
// Angular will display the text, not execute the script
userInput = '<script>alert("XSS")</script>';
}DomSanitizer - Conscious Bypass
Sometimes you need to display trusted HTML (e.g., from a WYSIWYG editor):
import { DomSanitizer, SafeHtml, SafeUrl } from '@angular/platform-browser';
@Component({
template: `
<!-- Using pipe or binding -->
<div [innerHTML]="trustedHtml"></div>
<iframe [src]="trustedUrl"></iframe>
`
})
export class TrustedContentComponent {
private sanitizer = inject(DomSanitizer);
trustedHtml: SafeHtml;
trustedUrl: SafeUrl;
constructor() {
// IMPORTANT: Use only for TRUSTED sources!
this.trustedHtml = this.sanitizer.bypassSecurityTrustHtml(
'<b>Trusted HTML</b>'
);
this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(
'https://trusted-site.com/embed'
);
}
}
// Reusable pipe
@Pipe({ name: 'safeHtml', standalone: true })
export class SafeHtmlPipe implements PipeTransform {
private sanitizer = inject(DomSanitizer);
transform(value: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}Content Security Policy (CSP)
CSP is an additional layer of defense - like the outer walls of the castle:
<!-- index.html -->
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
">Protection Against CSRF
// app.config.ts
import { provideHttpClient, withXsrfConfiguration } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withXsrfConfiguration({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
})
)
]
};Code for this lesson: src/app/app.component.ts
import { Component, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<div class="security-castle">
<h1>Castle Fortifications - Angular Security</h1>
<section class="xss-demo">
<h2>XSS Protection</h2>
<div class="demo-box">
<h3>Angular automatic sanitization</h3>
<div class="input-group">
<label>Enter text (try <script> or onclick):</label>
<input
type="text"
[value]="userInput()"
(input)="onInputChange($event)"
placeholder="<script>alert('XSS')</script>"
>
</div>
<div class="output-comparison">
<div class="output safe">
<h4>Angular default (safe):</h4>
<div class="content">{{ userInput() }}</div>
<p class="note">Angular automatically escapes HTML</p>
</div>
<div class="output dangerous">
<h4>innerHTML without sanitization:</h4>
<div class="content" [innerHTML]="userInput()"></div>
<p class="note">Angular sanitizes innerHTML automatically</p>
</div>
<div class="output bypass">
<h4>bypassSecurityTrust (be careful!):</h4>
<div class="content" [innerHTML]="trustedHtml()"></div>
<p class="note">Only for trusted sources!</p>
</div>
</div>
</div>
</section>
<section class="sanitizer-api">
<h2>DomSanitizer API</h2>
<div class="methods-grid">
<div class="method">
<code>bypassSecurityTrustHtml()</code>
<p>Trusted HTML</p>
</div>
<div class="method">
<code>bypassSecurityTrustStyle()</code>
<p>Trusted CSS styles</p>
</div>
<div class="method">
<code>bypassSecurityTrustScript()</code>
<p>Trusted script</p>
</div>
<div class="method">
<code>bypassSecurityTrustUrl()</code>
<p>Trusted URL</p>
</div>
<div class="method">
<code>bypassSecurityTrustResourceUrl()</code>
<p>Trusted resource URL (iframe)</p>
</div>
</div>
<div class="warning-box">
<h3>Warning</h3>
<p>Never use bypass* for user data! Only for trusted, controlled sources.</p>
</div>
</section>
<section class="code-example">
<h2>Secure code example</h2>
<pre><code>{{ safeCodeExample }}</code></pre>
</section>
<section class="checklist">
<h2>Security Checklist</h2>
<ul>
@for (item of securityChecklist(); track item.id) {
<li [class.checked]="item.checked" (click)="toggleCheck(item.id)">
<span class="checkbox">{{ item.checked ? '[x]' : '[ ]' }}</span>
<span class="text">{{ item.text }}</span>
</li>
}
</ul>
<p class="progress">
Completed: {{ checkedCount() }}/{{ securityChecklist().length }}
</p>
</section>
</div>
`,
styles: [`
.security-castle {
font-family: 'Segoe UI', sans-serif;
padding: 20px;
background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
min-height: 100vh;
color: #ecf0f1;
}
h1 {
text-align: center;
color: #e74c3c;
}
h2 {
color: #e74c3c;
border-bottom: 2px solid #e74c3c;
padding-bottom: 10px;
}
section {
background: rgba(255,255,255,0.05);
border-radius: 10px;
padding: 20px;
margin: 20px 0;
}
.demo-box {
background: rgba(0,0,0,0.3);
padding: 20px;
border-radius: 8px;
}
.input-group {
margin-bottom: 20px;
}
.input-group label {
display: block;
margin-bottom: 8px;
color: #bdc3c7;
}
.input-group input {
width: 100%;
padding: 12px;
border: 2px solid #34495e;
border-radius: 5px;
background: #2c3e50;
color: white;
font-size: 16px;
box-sizing: border-box;
}
.output-comparison {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
}
.output {
padding: 15px;
border-radius: 8px;
}
.output.safe {
background: rgba(46, 204, 113, 0.2);
border: 2px solid #2ecc71;
}
.output.dangerous {
background: rgba(241, 196, 15, 0.2);
border: 2px solid #f1c40f;
}
.output.bypass {
background: rgba(231, 76, 60, 0.2);
border: 2px solid #e74c3c;
}
.output h4 {
margin-top: 0;
font-size: 0.9em;
}
.output .content {
background: rgba(0,0,0,0.3);
padding: 10px;
border-radius: 4px;
min-height: 40px;
word-break: break-all;
}
.output .note {
font-size: 0.8em;
color: #888;
margin-bottom: 0;
}
.methods-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin: 20px 0;
}
.method {
background: rgba(0,0,0,0.3);
padding: 15px;
border-radius: 8px;
text-align: center;
}
.method code {
display: block;
background: #e74c3c;
color: white;
padding: 8px;
border-radius: 4px;
margin-bottom: 10px;
font-size: 0.85em;
}
.method p {
margin: 0;
color: #bdc3c7;
}
.warning-box {
background: rgba(231, 76, 60, 0.2);
border: 2px solid #e74c3c;
border-radius: 8px;
padding: 15px;
}
.warning-box h3 {
margin-top: 0;
color: #e74c3c;
}
pre {
background: #1a252f;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
border-left: 4px solid #e74c3c;
}
code {
color: #ecf0f1;
font-family: 'Fira Code', monospace;
font-size: 0.85em;
}
.checklist ul {
list-style: none;
padding: 0;
}
.checklist li {
display: flex;
align-items: center;
gap: 10px;
padding: 12px;
margin: 5px 0;
background: rgba(0,0,0,0.3);
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
}
.checklist li:hover {
background: rgba(0,0,0,0.5);
}
.checklist li.checked {
background: rgba(46, 204, 113, 0.2);
}
.checklist .checkbox {
font-size: 1.2em;
}
.progress {
text-align: center;
font-weight: bold;
color: #2ecc71;
}
`]
})
export class AppComponent {
userInput = signal('<b>Bold</b> <script>alert("XSS")</script> <img onerror="alert(1)" src="x">');
securityChecklist = signal([
{ id: 1, text: 'Do not use bypassSecurityTrust* for user data', checked: false },
{ id: 2, text: 'Validate data on the server side', checked: false },
{ id: 3, text: 'Use HttpOnly cookies for tokens', checked: false },
{ id: 4, text: 'Implement CSP (Content Security Policy)', checked: false },
{ id: 5, text: 'Sanitize URLs before use', checked: false },
{ id: 6, text: 'Avoid eval() and innerHTML with user data', checked: false },
{ id: 7, text: 'Use HTTPS everywhere', checked: false },
{ id: 8, text: 'Update Angular to the latest version', checked: false }
]);
checkedCount = computed(() =>
this.securityChecklist().filter(item => item.checked).length
);
safeCodeExample = `// Secure use of DomSanitizer
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({...})
export class SafeComponent {
private sanitizer = inject(DomSanitizer);
// For trusted HTML from server (e.g. CMS)
trustedContent: SafeHtml;
loadTrustedContent(): void {
// Only for content from a trusted source!
const htmlFromCMS = this.cmsService.getContent();
this.trustedContent = this.sanitizer.bypassSecurityTrustHtml(htmlFromCMS);
}
// NEVER do this for user data!
// userInput = this.sanitizer.bypassSecurityTrustHtml(userProvidedData);
// For dynamic URLs
getVideoUrl(videoId: string): SafeResourceUrl {
const url = \`https://youtube.com/embed/\${videoId}\`;
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}`;
constructor(private sanitizer: DomSanitizer) {}
trustedHtml = computed(() => {
// Demonstration - in practice use only for trusted sources!
return this.sanitizer.bypassSecurityTrustHtml(this.userInput());
});
onInputChange(event: Event): void {
const input = event.target as HTMLInputElement;
this.userInput.set(input.value);
}
toggleCheck(id: number): void {
this.securityChecklist.update(list =>
list.map(item =>
item.id === id ? { ...item, checked: !item.checked } : item
)
);
}
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How does Angular protect against XSS attacks?
2. What does the abbreviation XSS mean in the context of web application security?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the component that displays trusted HTML from a CMS.
- Horizontal ordering
Arrange the DomSanitizer import line in the correct order (left to right):
- Click in order
Build the call that returns trusted HTML (click in order):