Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Implementing CSRF Protection in Angular

Introduction

Cross-Site Request Forgery (CSRF) is a type of attack that tricks the victim into submitting a request that they did not intend to make. This lesson covers how to implement CSRF protection in Angular applications to safeguard against this type of attack.

What is CSRF?

CSRF attacks exploit the trust a web application has in the user's browser. They can lead to unauthorized actions being performed on behalf of the user without their consent.

Key Takeaway: Always ensure that sensitive actions are protected against CSRF to maintain user safety.

Angular CSRF Protection

Angular provides built-in support for CSRF protection by utilizing CSRF tokens. A CSRF token is a unique, secret, and unpredictable value generated by the server and sent to the client. The client then sends this token back to the server with each state-changing request.

Step-by-Step Implementation

  1. Generate CSRF Token on the Server:
    
    // Example with Node.js and Express
    const csrf = require('csurf');
    const csrfProtection = csrf({ cookie: true });
    app.use(csrfProtection);
    app.get('/api/csrf-token', (req, res) => {
        res.json({ csrfToken: req.csrfToken() });
    });
                    
  2. Fetch CSRF Token in Angular:
    
    // In your Angular service
    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    
    @Injectable({
        providedIn: 'root'
    })
    export class TokenService {
        constructor(private http: HttpClient) {}
        
        fetchCsrfToken() {
            return this.http.get<{ csrfToken: string }>('/api/csrf-token');
        }
    }
                    
  3. Include CSRF Token in Requests:
    
    // In your Angular HTTP interceptor
    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class CsrfInterceptor implements HttpInterceptor {
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
            const csrfToken = localStorage.getItem('csrfToken'); // Assume you stored it in localStorage
            if (csrfToken) {
                req = req.clone({
                    setHeaders: {
                        'X-CSRF-Token': csrfToken
                    }
                });
            }
            return next.handle(req);
        }
    }
                    
  4. Handle CSRF Errors:
    
    // In your Angular service
    this.http.post('/api/submit', data).subscribe({
        next: response => console.log('Success', response),
        error: (err) => {
            if (err.status === 403) {
                console.error('CSRF token is invalid or missing.');
            }
        }
    });
                    

Best Practices

  • Always validate CSRF tokens on the server-side.
  • Store CSRF tokens securely, using HttpOnly and Secure flags if using cookies.
  • Regenerate CSRF tokens after a successful login or sensitive action.
  • Implement a Content Security Policy (CSP) to mitigate attacks further.
  • Educate users about safe browsing practices to reduce attack risk.

FAQ

What happens if CSRF protection is not implemented?

Without CSRF protection, attackers can perform unauthorized actions on behalf of users, potentially leading to data theft or loss, account compromise, and other malicious activities.

Is CSRF protection only necessary for state-changing requests?

Yes, CSRF protection is primarily necessary for state-changing requests (e.g., POST, PUT, DELETE). However, it is a good practice to apply it on all requests that modify data.

Can CSRF tokens be stored in localStorage?

While you can store CSRF tokens in localStorage, it is recommended to use HttpOnly cookies for better security against XSS attacks.