1

I have Angular 13 application and backend using ruby on rails. According to the Angular documentation https://angular.io/api/common/http/HttpClientXsrfModule#description, I should be able to simply use HttpClientXsrfModule for the XSRF protection. It has optional setting for cookieName and headerName. The problem is that in my case there is no CSRF cookie, the token is stored in the page header META tag. That's why I think that it's not possible to use HttpClientXsrfModule as documentation says.

Instead I'm going to implement a custom interceptor, however I have no idea how to get META tag value within Angular custom interceptor. https://angular.io/guide/http#intercepting-requests-and-responses

Please advice how can I get page header META tag value within Angular interceptor:

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class NoopInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    req = req.clone({
            setHeaders: { 'X-CSRF-TOKEN': ...how to get it... }
        });
    return next.handle(req);
  }
}
4

1 回答 1

1

Angular 提供了Meta Service,使用它我们可以检索 meta 元素。

import { Meta } from '@angular/platform-browser';
import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  constructor(private meta:Meta){
    console.log(this.meta.getTag('name="csrf-token"').content);
  }
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    req = req.clone({
            setHeaders: { 'X-CSRF-TOKEN': this.meta.getTag('name="csrf-token"').content }
        });
    return next.handle(req);
  }
}
于 2021-12-09T04:43:42.610 回答