</>
Skip to content
Angular lessons (43/43)

Angular — Security

XSS Protection

Angular automatically sanitizes output:

<!-- Safe - automatically sanitized -->
<div>{{userInput}}</div>

<!-- Dangerous - bypasses sanitizer -->
<div [innerHTML]="trustedHtml"></div>

Sanitization

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

@Component({ ... })
export class MyComponent {
  constructor(private sanitizer: DomSanitizer) {}
  
  getTrustedHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

CSRF Protection

// Angular handles CSRF automatically with HttpClient
// It reads the XSRF-TOKEN cookie

HTTP Security

// Use HTTPS
const apiUrl = 'https://api.example.com';

// Add security headers
const headers = new HttpHeaders({
  'X-Content-Type-Options': 'nosniff',
  'X-Frame-Options': 'DENY'
});

Input Validation

form = new FormGroup({
  email: new FormControl('', [Validators.required, Validators.email]),
  password: new FormControl('', [
    Validators.required,
    Validators.minLength(8),
    Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
  ])
});

Security Checklist

PracticeDescription
Sanitize outputPrevent XSS
Use HTTPSEncrypt data
Validate inputPrevent injection
Store tokens securelyHttpOnly cookies
Implement CORSControl access

Mini Practice

  1. Sanitize user input
  2. Add security headers
  3. Validate forms
  4. Implement CORS

Up Next

Congratulations! You've completed the Angular course.

Related Topics

Frequently Asked Questions about Security

What is Security in Angular?

Security is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Security?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Security.

Why is Security important in Angular?

Security is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.