Enabling Cross-Site Request Forgery (CSRF) through Angular's HttpClientModule is causing an error message to appear: TS2552 -

As a novice in front-end development, I am looking to incorporate CSRF tokens into certain requests within a frontend application. The app is built using Angular version 12.2.17, and I am following the guidelines outlined in the Angular documentation: https://angular.io/api/common/http/HttpClientXsrfModule

To implement this, I have added the interceptor in my code as shown below:

import {HTTP_INTERCEPTORS, HttpClientModule, HttpClientXsrfModule  } from "@angular/common/http";


imports: [
        ...
        HttpClientXsrfModule
    ],
providers: [
         ...
        { provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true }
    ],

However, upon adding the "HttpXsrfInterceptor" line, I encountered an error tooltip in IntelliJ:

TS2552: Cannot find name  HttpXsrfInterceptor . Did you mean HTTP_INTERCEPTORS ?

What adjustments do I need to make to properly configure the HttpXsrfInterceptor?

What I have tried:

As an attempt to solve the issue, I modified the imports line to include:

import {HTTP_INTERCEPTORS, HttpClientModule, HttpClientXsrfModule, HttpXsrfInterceptor } from "@angular/common/http";

This change, however, resulted in another error message related to the mentioned line:

TS2724:  "@angular/common/http"  has no exported member named  HttpXsrfInterceptor . Did you mean  HTTP_INTERCEPTORS ?

Answer №1

Success! After much trial and error, the code finally compiled successfully:

import {CustomHttpInterceptor} from "./custompath/myinterceptor";
...

 providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomHttpInterceptor,
      multi: true
    }
  ]

The CustomHttpInterceptor is a unique interceptor implementation shown below:

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

  constructor( 
    private tokenExtractor: HttpXsrfTokenExtractor
  ) {}

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

    Observable<HttpEvent<any>> {
      console.log("custom interceptor active");
      const cookieheaderName = 'X-CSRF-TOKEN';
      let csrfToken = this.tokenExtractor.getToken() as string;
      console.log("custom csrfToken: " + csrfToken);
      if (csrfToken !== null && !req.headers.has(cookieheaderName)) {
          console.log("custom cloning request with CSRF token: " + csrfToken);
          req = req.clone({ headers: req.headers.set(cookieheaderName, csrfToken) });
      }
      console.log("custom returning request's handling");

    return next.handle(req);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for ensuring that CSS hover effects stay in place even when the page is scrolled

i'm having trouble with a project in React JS that I received from another team. I'm not very confident in my skills with React JS, and I'm facing an issue where a certain part of the page is supposed to change to red when hovered over. Howe ...

Why is this chip-list not functioning properly in my Angular 14 and Angular material application?

I'm currently developing a form using Angular 14. My goal is to incorporate a field with Angular Material chips. Within the component's Typescript file, I have the following code: constructor(private fb: FormBuilder,) { } public visible: boole ...

Ways to utilize and display data in a *ngFor loop

I have created a simple service for accessing an HTTP service. Can anyone help me with how to bind this service information in *ngFor? import { Component } from '@angular/core'; import {Http } from '@angular/http'; import { In ...

Dealing with Undefined TypeScript Variables within an array.forEach() loop

Could someone help me understand my issue? I have an array of a specific object, and I am trying to create a new array with just the values from a particular field in each object. I attempted to use the forEach() method on the array, but I keep encounteri ...

The wss websocket connection is experiencing issues in Firefox 89 when attempting to connect on localhost

For some reason, the websocket wss connection is not working in Firefox 89 when trying to connect on localhost. Interestingly, I can successfully establish a connection using my to connect to from the production server. However, when attempting to init ...

Restricting Set-Cookie in DRF SessionAuthentication and React during development mode

I have a very specific query that I haven't come across in the numerous inquiries about this particular topic. Initially, my Set-Cookie headers were being blocked. However, even after resolving that issue, the Cookies are still not being stored and I ...

Fetching data from an API using Observables in Angular

I am facing a challenge with an API endpoint that returns an array of strings in JSON format. My goal is to display these contents on a webpage using an Angular Service. Below is the code snippet I have implemented so far (working with Angular 7): export ...

What is the best way to showcase the chosen information?

Typically, I maintain a list of specific entries within cards. When clicking on one of the records in the card, the corresponding data table is supposed to be displayed below that record. An issue arises where after selecting a record and displaying its d ...

utilizing type predictors in brand merging

For hours now, I've been struggling with a small problem that seems to have no solution in sight. I wonder if someone with a sharper mind could offer me some guidance? The method I'm using returns a predicate: this is xxx. This method is then us ...

how to share a variable across multiple ts files in an Angular project

In the home.component.ts file, I have a variable named name that I want to access globally in all files. Can anyone please suggest how can I achieve this? Below is the code snippet: app.component.html <nav aria-label="breadcrumb"> <ol class= ...

Issue with Angular 2 AOT Compilation when trying to access formArray

This is the formGroup I created this.createOrderForm = this.fb.group({ items: this.fb.array([]) }); To add an item on button click addItem() { const control = <FormArray>this.createOrderForm.controls['items']; const a ...

Using Jest and TypeScript to mock the return value of react-oidc-context

For our project, we utilize react-oidc-context to handle user authentication using oidc-client-ts under the hood. The useAuth function provided by react-oidc-context gives us access to important information such as isAuthenticated, isLoading, and the auth ...

What is the advantage of utilizing the ng-idle library for monitoring user idle status when we have the ability to create custom JavaScript code to track inactivity based on keyboard and mouse events?

I have implemented a method to detect user idle time using mouse and key events as shown below. @HostListener('window:keydown', ['$event']) @HostListener('window:mousedown', ['$event']) @HostListener('window:mou ...

Angular4 + Universal + ng-bootstrap triggering an 'Unexpected token import' error

I recently made the leap to upgrade my angular version from 2+ to 4+ in order to take advantage of the universal package for server-side rendering, specifically for SEO purposes. Following the necessary steps and configurations outlined at https://github.c ...

Enhancing Type Safety in Typescript through Key/Property Type Guards

Is it possible to create a typeguard that can confirm the existence (or specific type) of a property in an object? For example: Consider an interface Foo: interface Foo { bar: string; baz: number; buzz?: string; } An object of type Foo may ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

How can I test Angular Router using Jest?

I'm currently experimenting with testing the functionality of a collapsed element in a sidebar when a user navigates to a specific page. I'm encountering some challenges in trying to simulate the behavior of the Angular Router in my Jest tests. ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

Angular loop is unable to detect changes in the updated list

My Angular application is facing a peculiar issue that I can't seem to figure out. // Here are the class attributes causing trouble tenants: any[] = []; @Input() onTenantListChange: EventEmitter<Tenant[]>; ngOnInit(): void { this. ...

Incorporate a linked select dropdown into the registration form

I am working on a sign-up form and trying to integrate 2 linked select boxes into the form. The code for the linked select boxes works fine separately but when I attempt to add it to the form, it doesn't display as expected. I attempted to incorporate ...