Home > OS >  Angular 13 CSRF Token from page META tag
Angular 13 CSRF Token from page META tag

Time:12-09

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);
  }
}

CodePudding user response:

Angular provides Meta Service,Using this we can retrieve meta element.

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);
  }
}
  • Related