Secure Coding Practices in Angular

Secure Coding Practices in Angular

1. Prevent Cross-Site Scripting (XSS)

Angular auto-escapes content in {{ }}, but avoid using untrusted data with [innerHTML].

<!-- Safe -->

<p>{{ userInput }}</p>

 

<!-- Risky: must sanitize -->

<div [innerHTML]="sanitizedHtml"></div>

constructor(private sanitizer: DomSanitizer) {}

this.sanitizedHtml = this.sanitizer.bypassSecurityTrustHtml(userInput);

 

2. CSRF Protection (for cookie-based auth)

If the API uses cookies for auth, Angular must:

  • Send requests with withCredentials: true
  • Include the anti-forgery token in headers

this.http.post(url, data, { withCredentials: true });

 

3. Store and Protect Tokens

Avoid storing tokens in localStorage. Prefer HttpOnly cookies, or use in-memory storage with auto-refresh logic.

 

4. Route Guards for Authorization

Use route guards to protect client-side routes based on user roles.

canActivate(): boolean {

  return this.authService.getUserRole() === 'Admin';

}

 

5. Handle Token Expiry with Interceptors

Automatically refresh JWT tokens when expired using HTTP interceptors.

intercept(req: HttpRequest<any>, next: HttpHandler) {

  if (this.authService.isTokenExpired()) {

    return this.authService.refreshToken().pipe(

      switchMap(() => next.handle(this.addAuthHeader(req)))

    );

  }

  return next.handle(this.addAuthHeader(req));

}

 

6. Use HTTPS

Serve Angular applications over HTTPS in production environments. Ensure API calls are made over https://.

 

Summary

Angular (Frontend)

  • Escape and sanitize output
  • Use route guards and token interceptors
  • Avoid exposing tokens in localStorage
  • Serve over HTTPS
  • Handle CSRF if cookies are used

Comments

Popular posts from this blog

Factory Method Design Pattern in .NET — Real-Time Finance Example

Logging in .NET Core: Built-in Logging vs Serilog with Full Implementation Guide

Implementing Single Sign-On (SSO) in .NET Core and Angular