enabling CSRF via Angular HttpClientModule, error: TS2552: Cannot find name HttpXsrfInterceptor

92 views Asked by At

Question comming from a front-end beginner. I would like to add csrf tokens to some of the requests in a frontend app. The application is using Angular in version 12.2.17. I follow instructions from Angular documentation: https://angular.io/api/common/http/HttpClientXsrfModule

In the code I am adding the interceptor as follows:

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


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

When I do that, the line with "HttpXsrfInterceptor" is triggering error tooltip in IntelliJ:

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

What should I change to configure the HttpXsrfInterceptor correctly?

What I have tried:

If I try to change the imports line to :

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

Then I am getting another error message from the mentioned line:

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

1

There are 1 answers

0
fascynacja On

Finally the code which compiled without error is:

import {GlobalHttpInterceptorInterceptor} from "./pathto/myinterceptor";
...

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

where GlobalHttpInterceptorInterceptor is an interceptor defined as:

@Injectable()
export class GlobalHttpInterceptorInterceptor implements HttpInterceptor {

  constructor( 
    private tokenExtractor: HttpXsrfTokenExtractor
  ) {}

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

    Observable<HttpEvent<any>> {
      console.log("global intercept  ");
      const cookieheaderName = 'X-CSRF-TOKEN';
      let csrfToken = this.tokenExtractor.getToken() as string;
      console.log("global csrfToken: " + csrfToken);
      if (csrfToken !== null && !req.headers.has(cookieheaderName)) {
          console.log("global cloning request for : " + csrfToken);
          req = req.clone({ headers: req.headers.set(cookieheaderName, csrfToken) });
      }
      console.log("global return the handling");

    return next.handle(req);
  }
}