Angular 5配置CSP需添加'unsafe-eval'?能否保留禁用eval的安全特性?
'unsafe-eval'? Let's break down your questions clearly—this is a common pain point when locking down CSP for Angular apps:
1. Does Angular 5 itself use eval()?
It all comes down to whether you're running in JIT (Just-in-Time) or AOT (Ahead-of-Time) compilation mode:
- JIT Mode (typically development environments): Angular compiles component templates dynamically in the browser. This process relies on mechanisms like
eval()ornew Function()under the hood, so you will need'unsafe-eval'in yourscript-srcdirective to avoid the error you're seeing. - AOT Mode (production recommended): Templates are compiled into static JavaScript during the build process, not at runtime. There's no dynamic compilation happening, so Angular never touches
eval()or similar functions. This means you can safely omit'unsafe-eval'from your CSP for production builds.
2. Does the GitHub Issue about SystemJS apply to my Webpack setup?
That issue focuses on SystemJS-based Angular apps, which have different runtime requirements. For Webpack-built Angular 5 apps, the story is simpler: when using AOT compilation (which is the default for ng build --prod), Webpack pre-compiles all your templates into static code. There's no runtime compilation step that would trigger the CSP eval restriction, so that issue doesn't apply here.
3. How to configure CSP safely for both environments?
- Development: Since you're likely using JIT, update your CSP meta tag to include
'unsafe-eval'inscript-src:<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-eval'; img-src 'self' data:; media-src 'self'; object-src 'self' data:; style-src 'self' https://fonts.googleapis.com 'unsafe-inline';"> - Production: Stick with AOT builds (Angular CLI's production build enables this by default), then you can keep a strict CSP without
'unsafe-eval':
Quick note on<meta http-equiv="Content-Security-Policy" content="script-src 'self'; img-src 'self' data:; media-src 'self'; object-src 'self' data:; style-src 'self' https://fonts.googleapis.com 'unsafe-inline';">'unsafe-inline'for styles: Angular 5's style binding may still require this in some cases, even with AOT. You can experiment with removing it later if all your styles are static or use Angular's style encapsulation, but for now it's safer to keep it.
Final Takeaway
For production builds of your Webpack-based Angular 5 app using AOT compilation, you do NOT need 'unsafe-eval'—you can maintain the strict security of your CSP. Only development environments using JIT require the exception.
内容的提问来源于stack exchange,提问作者Mark Sandman

