Security is one of the most important aspects of a modern web application. Angular provides several in-built mechanisms to prevent common attacks such as XSS, CSRF, Clickjacking, and more.
Angular automatically escapes HTML to prevent XSS vulnerabilities.
If you must display HTML, use Angular’s DomSanitizer carefully.
constructor(private sanitizer: DomSanitizer) {}
safeHtml = this.sanitizer.bypassSecurityTrustHtml(userInput);
Use JWT tokens and validate on the backend. Never trust the frontend alone.
Used to protect routes from unauthorized access.
@Injectable({
providedIn: "root"
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (!this.auth.isLoggedIn()) {
this.router.navigate(["/login"]);
return false;
}
return true;
}
}
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
const token = localStorage.getItem("token");
const clone = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next.handle(clone);
}
}
Angular provides strong tools for security, but proper backend validation is always required.
Take quizzes related to this topic and see where you stand!
Start Quiz Now