How to Configure CSRF Prevention with Django and Angular

  • Add the {% csrf_token %} template tag so [Django] will set the csrftoken cookie
  • Serve index.html as a Django template by adding the directory and proper loader to the [Django] settings
  • Use django.shortcuts.render to render the file as a template.
  • On the Angular side the key is HttpClientXsrfModule, which allows you to customize both the cookie name and header name, but will otherwise take care of adding the header to all of your calls.
HttpClientXsrfModule.withOptions({
  cookieName: 'csrftoken',
  headerName: 'X-CSRFToken',
})