旅游网站开发指导,做多国语言网站,dw建设网站的代码模板下载,wordpress更换主题方法一#xff1a;错误出现 这个错误的意思是#xff0c;拒绝将字符串评估为 JavaScript#xff0c;因为‘unsafe-eval’不是以下内容安全策略中允许的脚本源。 二#xff1a;错误场景 testEval() {const data eval(var sum2 new Function(a, b, return a b); sum2(em… 一错误出现 这个错误的意思是拒绝将字符串评估为 JavaScript因为‘unsafe-eval’不是以下内容安全策略中允许的脚本源。 二错误场景 testEval() {const data eval(var sum2 new Function(a, b, return a b); sum2(email, eval););const sum new Function(a, b, return a b);console.log(test eval:, data);}类似的不安全的表达式还有 eval()Function() ——When passing a string literal like to methods like: setTimeout(alert(\Hello World!\);, 500);setTimeout()setInterval()window.setImmediatewindow.execScript() (IE 11 only) 三错误原因 因为我的安全策略CSP白名单中并不包含‘unsafe-eval’这个选项。所以抛出了异常。 不包含‘unsafe-eval’的理由是eval 实际上是不安全的。 它在每种语言中的意思是“获取这个字符串并执行它的代码”。 也就是说eval本质是将字符串转成表达式并执行。容易遭到注入攻击。 四错误解决 1尽量避免使用eval方法大多数情况下eval方法是可以被避免的。可以使用lint检查项目中是否含有eval方法 no-eval - ESLint - Pluggable JavaScript Linter 上述的代码可以这样更改代码正常工作 testEval(): string {const sum1: Function (a: string, b: string) { return a b };return sum1(test, eval);}2如果有时候必须动态生成方法这部分工作可以放到服务端完成。而不是把‘unsafe-eval’加入到CSP白名单中。 上述代码还可以这样更改代码正常工作 testEvalSolutionTwo(): ObservableObject {return this.http.get(this.rootURL /test/eval);}五CSP的配置补充 CSP可以在三个地方配置 1拦截器 import { requestInterceptor } from ./http/request.intercepter;
NgModule({.. .. ..providers: [{provide: HTTP_INTERCEPTORS,useClass: requestInterceptor,multi: true}],bootstrap: [AppComponent]
})
export class AppModule { }import { Injectable } from angular/core;
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent } from angular/common/http;
import { Observable } from rxjs;Injectable()
export class requestInterceptor implements HttpInterceptor {constructor() {}intercept(req: HttpRequestany, next: HttpHandler): ObservableHttpEventany {req.headers.append(Content-security-policy, script-src self;);return next.handle(req);}
}2html文件 meta http-equivContent-Security-Policy contentdefault-src self; child-src none; 3server端推荐 app.use(function (req, res, next) {res.setHeader(Content-security-policy,script-src self; connect-src self;,);next();
});CSP文档参见CSP: script-src - HTTP | MDN