2

Some of the responses from service workers are violating the CSP, and I may need to add this header:

Content-Security-Policy = "connect-src *;"

to all the responses from service workers as explained here and here.

How can I add response headers to service worker responses using angular PWA?

ChrisOdney
  • 6,066
  • 10
  • 38
  • 48

2 Answers2

1

You can use http interceptors for intercepting any kind of http request & response in one place. It is also applicable for service workers.

Please find a detailed explanation here.

https://angular.io/api/common/http/HttpInterceptor

Example:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
    ...          
));
}
talhature
  • 2,246
  • 1
  • 14
  • 28
  • I did not know interceptors work for service workers(fetch requests) too, will give it a shot. – ChrisOdney Jun 21 '19 at 09:25
  • 1
    This won't work. CSP headers have to be set on the server before the responses ever make it to the client/Angular code. – abraham Jun 23 '19 at 17:48
  • @abraham Headers are being sent from the server but when these are cached and served from service workers those headers are not there. – ChrisOdney Jun 24 '19 at 01:22
0

The response headers need not be set on the cached response returned by the service worker, instead the solution is to set special CSP headers on the server to the response for the SW script. I.e., when the browsers requests ngsw-worker.js (the default name for the Angular SW script), the server should attach special CSP headers (e.g. Content-Security-Policy: connect-src *) to that response.

ChrisOdney
  • 6,066
  • 10
  • 38
  • 48
  • This. It's not Angular specific. Note that you probably also need worker-src, not connect-src, although in my case the error said the latter the fix was the former. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/worker-src – philw Oct 29 '20 at 15:35