angular4 httpclient csrf does not send x-xsrf-token

前端 未结 3 1131
猫巷女王i
猫巷女王i 2020-12-02 21:06

In angular documentation, it is mentioned that the angular httpclient will automatically send the value of cookie XSRF-TOKEN in the header X-

相关标签:
3条回答
  • 2020-12-02 21:18

    I suppose the correct method is withOptions. I used withConfig and got error Property 'withConfig' does not exist on type 'typeof HttpClientXsrfModule'. This is a typing issue in the documentation. You need to use "withOptions" instead HttpClientXsrfModule.withOptions({ cookieName: 'My-Xsrf-Cookie', headerName: 'My-Xsrf-Header', })

    0 讨论(0)
  • 2020-12-02 21:22

    Using the recent Angular version I ran into the following problem. While the token is passed to the client using the header name 'XSRF-TOKEN', the response must feed back the token using the header name 'X-XSRF-TOKEN'. So here is a slightly modified version of Miroslav's code above which works for me.

    @Injectable()
    export class HttpXSRFInterceptor implements HttpInterceptor {
    
      constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
      }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const headerName = 'XSRF-TOKEN';
        const respHeaderName = 'X-XSRF-TOKEN';
        let token = this.tokenExtractor.getToken() as string;
        if (token !== null && !req.headers.has(headerName)) {
          req = req.clone({ headers: req.headers.set(respHeaderName, token) });
        }
        return next.handle(req);
      }
    }
    
    0 讨论(0)
  • 2020-12-02 21:40

    What you are looking for is HttpClientXsrfModule.

    Please read more about it here: https://angular.io/api/common/http/HttpClientXsrfModule.

    Your usage should be like this:

    imports: [   
     HttpClientModule,  
     HttpClientXsrfModule.withOptions({
       cookieName: 'My-Xsrf-Cookie', // this is optional
       headerName: 'My-Xsrf-Header' // this is optional
     }) 
    ]
    

    Additionally, if your code targets API via absolute URL, default CSRF interceptor will not work out of the box. Instead you have to implement your own interceptor which does not ignore absolute routes.

    @Injectable()
    export class HttpXsrfInterceptor implements HttpInterceptor {
    
      constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
      }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const headerName = 'X-XSRF-TOKEN';
        let token = this.tokenExtractor.getToken() as string;
        if (token !== null && !req.headers.has(headerName)) {
          req = req.clone({ headers: req.headers.set(headerName, token) });
        }
        return next.handle(req);
      }
    }
    

    And finally add it to your providers:

    providers: [
      { provide: HTTP_INTERCEPTORS, useClass: HttpXsrfInterceptor, multi: true }
    ]
    
    0 讨论(0)
提交回复
热议问题