Blog>
Snippets

Adding CSRF Token in Angular Forms

Illustrate how to include a CSRF token within an Angular form by binding a hidden form field to a token value.
import { HttpClientXsrfModule } from '@angular/common/http';

@NgModule({
  imports: [
    // Import HttpClientXsrfModule with appropriate configuration
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN', // This is the name of the cookie to read to get the token.
      headerName: 'X-XSRF-TOKEN' // This is the name of the HTTP header to add with the token.
    }),
    // ... other imports
  ],
  // ... other metadata
})
export class AppModule { }
This code configures the HttpClientXsrfModule to include CSRF tokens in HTTP requests. Replace 'XSRF-TOKEN' and 'X-XSRF-TOKEN' with the actual names of your CSRF token cookie and header.
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-csrf-form',
  template: `
    <form (ngSubmit)="submitForm()">
      <!-- Hidden input to bind CSRF token -->
      <input type="hidden" name="csrf" [value]="csrfToken" />
      <!-- Other form inputs -->
    </form>`
})
export class CsrfFormComponent implements OnInit {
  csrfToken: string;

  constructor(private http: HttpClient) { }

  ngOnInit() {
    // Fetch CSRF token from server and assign it to the csrfToken property
  }

  submitForm() {
    // Submit form with CSRF token included
  }
}
This Angular component sets up a form with a hidden input element that contains the CSRF token. The token is fetched from the server on initialization and bound to the hidden input's value attribute. The form submission includes the CSRF token, providing protection against CSRF attacks.