Posted on: January 19, 2025 Posted by: rahulgite Comments: 0

This section covers detailed explanations, examples, and implementation steps for 20 key security-related questions in Angular.


1. How do you protect against Cross-Site Scripting (XSS) in Angular?

Answer

Angular provides built-in DOM sanitization to prevent XSS attacks by default. Angular automatically escapes data bound to templates using interpolation or property binding.

Steps to Implement

  1. Avoid manually inserting untrusted content into the DOM.
  2. Use Angular bindings ({{ }} or [property]) to ensure data is sanitized.
  3. If absolutely necessary to bypass sanitization (e.g., trusted HTML), use DomSanitizer.

Example

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

@Component({
  selector: 'app-xss-demo',
  template: `<div [innerHTML]="trustedHtml"></div>`
})
export class XssDemoComponent {
  trustedHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer) {
    const maliciousHtml = '<script>alert("XSS")</script>';
    this.trustedHtml = this.sanitizer.bypassSecurityTrustHtml(maliciousHtml);
  }
}

2. What is DOM sanitization in Angular?

Answer

DOM sanitization ensures that Angular removes or modifies potentially malicious content before rendering it in the browser.

Key Concepts

  • Angular sanitizes HTML, URLs, styles, and scripts bound to templates.
  • Sanitization is applied to bindings like [innerHTML] or [src].

3. How do you secure API calls in Angular?

Answer

To secure API calls, you should use HTTPS, implement token-based authentication (e.g., JWT), and handle sensitive data carefully.

Steps to Implement JWT Authentication

  1. Obtain a token upon user login.
  2. Attach the token to API requests using an HTTP interceptor.
  3. Validate the token on the backend.

Example

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = localStorage.getItem('authToken');
    const clonedRequest = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` }
    });
    return next.handle(clonedRequest);
  }
}

4. What is CSRF, and how does Angular protect against it?

Answer

CSRF (Cross-Site Request Forgery) exploits user authentication to execute unauthorized actions. Angular provides built-in support for CSRF protection via tokens.

Steps to Implement

  1. Configure the server to send a CSRF token in a cookie.
  2. Angular’s HttpClient automatically attaches the CSRF token to subsequent requests.

5. How do you prevent sensitive data exposure in Angular?

Answer

  1. Never store sensitive data (e.g., tokens) in the browser.
  2. Use sessionStorage or encrypted cookies for temporary data storage.

6. How do you implement route guarding in Angular?

Answer

Route guards prevent unauthorized access to certain routes.

Types of Guards

  • canActivate
  • canDeactivate
  • canLoad

Example

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

7. How do you handle role-based access in Angular?

Answer

  1. Define user roles on the backend and include them in JWT tokens.
  2. Decode tokens in Angular and use route guards for role-based access.

8. What is the difference between JWT and OAuth2?

Answer

  • JWT: A token format for secure data exchange.
  • OAuth2: A protocol for authorization, often using JWT.

9. How does Angular help prevent template injection?

Answer

Angular escapes untrusted content automatically during data binding to prevent template injection.


10. What is Content Security Policy (CSP), and how does it protect Angular applications?

Answer

CSP is a browser feature that restricts the sources of content (scripts, styles, etc.) for an application.


11. How do you secure Angular applications from clickjacking?

Answer

Set X-Frame-Options headers on the server to DENY or SAMEORIGIN.


12. What are the best practices for securing Angular applications?

Answer

  • Use HTTPS.
  • Regularly update Angular.
  • Perform security audits.

13. What is HSTS, and why is it important?

Answer

HSTS enforces HTTPS by instructing browsers to refuse insecure connections.


14. How do you prevent third-party script execution in Angular?

Answer

Restrict sources using CSP and avoid eval() in code.


15. What is the difference between DomSanitizer and default sanitization?

Answer

DomSanitizer allows controlled bypassing of Angular’s default sanitization.


16. How do you prevent data leaks in Angular applications?

Answer

  1. Avoid logging sensitive data.
  2. Use secure cookies.

17. How do you secure WebSocket connections in Angular?

Answer

Use wss:// (WebSocket over SSL) and authenticate connections.


18. How does Angular handle CORS?

Answer

CORS is configured on the server. Angular sends CORS headers with cross-origin requests.


19. How do you prevent brute-force attacks on Angular applications?

Answer

Implement rate-limiting and CAPTCHA challenges.


20. What tools are used for securing Angular applications?

Answer

  • JWT for Authentication
  • OWASP ZAP for Security Audits
  • CSP

Leave a Comment