1

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')
        })
      );
      }
    }
4
  • How have you determined that "nothing gets added"? Commented Nov 11, 2021 at 15:35
  • 1
    Looking in the network tab in chrome I am looking at the response headers and the content security profile is not in the data. I was able to update the request headers, but not the response. Commented Nov 11, 2021 at 15:39
  • 1
    The network tab receive the response as it is returned by your backend, before that it is handled by your interceptor. If you want that response header you should add it server side Commented Nov 11, 2021 at 15:42
  • That was my guess, thank you! I have been going back and forth with our server side devs saying it needs to be done from their side, but just wanted to be sure I wasn't missing something obvious Commented Nov 11, 2021 at 15:46

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.