You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5配置CSP需添加'unsafe-eval'?能否保留禁用eval的安全特性?

Angular 5 + Content Security Policy: Do I Really Need '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() or new Function() under the hood, so you will need 'unsafe-eval' in your script-src directive 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' in script-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':
    <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';">
    
    Quick note on '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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:48:16