Home > Software design >  Set response headers from angular http interceptor
Set response headers from angular http interceptor

Time:11-12

I am trying to set a new header on every http response so the response includes a content-security-policy using the latest version of angular. I have created this http interceptor, and when I go to add to the header I don't get any errors or anything, but nothing actually gets added to the response headers. Here is the code I have for the interceptor. Is there anything that I should change here, or is it not possible to add response headers to every http response from angular.

  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { filter, map, tap } from 'rxjs/operators';

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {

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

      return next.handle(req).pipe(
        filter(event => event instanceof HttpResponse),
        tap((event: HttpResponse<any>) => {
          event.headers.append('content-security-policy', 'some content-security-policy')
        })
      );
      }
    }

CodePudding user response:

You can not alter history: The network tab shows what was sent across the network, and you can not retroactively change that.

What an HttpInterceptor can do is change its own copy of the received headers before passing it on to the subscriber.

Also, a content security header is interpreted by the browser before it passes the response to JavaScript.

  • Related