Make Angular working with restrictive Content Security Policy (CSP)

前端 未结 3 694
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 19:05

I cannot make base Angular2 (final) application works with the following restrictive CSP.

default-src \'none\';
script-src \'self\';
style-src \'self\';
font-src          


        
相关标签:
3条回答
  • 2021-02-03 19:26

    Edited answer for @angular/cli>=8.2

    From this Github thread, one can use the index property in angular.json to control the generation of the application's HTML index:

    build: {
      ...
      "configurations": {
        "production": {
          "index": {
            "input": "src/index.production.html",
             "output": "index.html"
           },
          ...
        }
      }
    }
    

    Original answer

    I've found a way to have restrictive CSP on my production environment while still being able to use the JTI compliler for development.

    • Add a second file: index.production.html to the src folder.
    • Copy the contents of index.html to that file, and add the restrictive CSP header.
    <meta http-equiv="Content-Security-Policy" 
    content="default-src 'none';
      frame-src 'self';
      script-src 'self';
      style-src 'self' 'unsafe-inline';
      font-src 'self';
      img-src 'self' data:;
      connect-src 'self'">
    
    • Then, add to your angular.json the following:
    build: {
      ...
      "configurations": {
        "production": {
          "fileReplacements": [
            {
              "replace": "src/index.html",
              "with": "src/index.production.html"
            }
          ],
          ...
        }
      }
    }
    

    This makes sure that when you run a production build, it will use the index.production.html with the restrictive CSP, and when you're running it locally, you can use the JTI compiler.

    0 讨论(0)
  • 2021-02-03 19:43

    The problem has been solved using last Angular CLI version (starting with 1.0.0-beta.17). The following command serves a working application because it includes a-head-of-time compilation.

    ng serve --prod
    
    0 讨论(0)
  • 2021-02-03 19:45

    Using the offline template compiler should fix this.

    http://www.syntaxsuccess.com/viewarticle/offline-compilation-in-angular-2.0 https://github.com/angular/angular/issues/1744

    0 讨论(0)
提交回复
热议问题