Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Angular Security — XSS, CSRF, and Sanitization

Security

Web development is not only about writing code that works just fine, it is also about writing code that works perfectly and is not prone to vulnerabilities. There are four key points to remember while developing any Angular applications-

1. Application Level Security:- To provide better application level security, we can do the following-

  • Use auth/route guards when required.

2. Prevent Cross Site Scripting (XSS):- Cross Site Scripting allows attackers to inject malicious script or code into web pages. To prevent XSS attacks, we must prevent the DOM from receiving malicious code. This type of attack is mostly executed via the query string, input fields, and request headers. To prevent XSS attacks, we can do the following in our Angular application-

  • Angular sanitization and security contexts.
  • Implement CSP (Content Security Policy).
  • Avoid interacting with DOM APIs directly.
  • Use the offline template compiler.

3. HTTP Level Vulnerabilities:- Angular comes with built-in support to help prevent common HTTP vulnerabilities, which include the following -

  • Cross site request forgery (XSRF).
  • Cross site script inclusion (XSSI).

Angular 21 Security Improvements

Angular 21 continues to improve security with the following built-in protections:

  • Trusted Types: Angular supports the Trusted Types API to prevent DOM-based XSS attacks.
  • Automatic Sanitization: Angular automatically sanitizes values bound to DOM properties that could execute scripts.
  • HttpClient XSRF Protection: Built-in CSRF token handling via withXsrfConfiguration().
  • Route Guards: Use functional guards with canActivate, canMatch, and canDeactivate.

Implementing Route Guards

Auth Guard
// auth.guard.ts - Functional guard (Angular 15+)
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  if (authService.isLoggedIn()) {
    return true;
  }

  // Redirect to login with return URL
  return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url }
  });
};

// app.routes.ts - Apply the guard
export const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] },
  { path: 'admin', component: AdminComponent, canActivate: [authGuard, adminGuard] },
  { path: 'login', component: LoginComponent },
];

// auth.service.ts - Token-based auth
@Injectable({ providedIn: 'root' })
export class AuthService {
  isLoggedIn(): boolean {
    const token = localStorage.getItem('auth_token');
    if (!token) return false;
    // Check token expiry
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      return payload.exp > Date.now() / 1000;
    } catch {
      return false;
    }
  }
}
Key Takeaways
  • Angular automatically sanitizes HTML, styles, and URLs bound to the DOM - never bypass this with bypassSecurityTrust unless absolutely necessary.
  • Use Angular\'s HttpClient for HTTP requests - it includes built-in XSRF/CSRF protection.
  • Never store sensitive data (passwords, tokens) in localStorage - use HttpOnly cookies for auth tokens.
  • Route guards (canActivate, canMatch) protect routes from unauthorized access.
  • Use Angular\'s DomSanitizer carefully - only sanitize values you fully control and trust.
  • Enable Content Security Policy (CSP) headers on your server to prevent XSS attacks.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.