Where should you configure Content Security Policy?

假装没事ソ 提交于 2019-12-10 19:09:34

问题


I have an angular application, that communicates with, depending on the setup, a REST API on Tomcat or a REST API on a Jetty. The angular-app itself is hosted on the same tomcat/jetty as a war.

The Tomcat setup might have an Apache in front (depending on the client)

The application needs to use base64 images (loaded trough css), but right now, if it's hosted on a server I get the following error:

Refused to load the image 'data:image/png;base64,...' because it violates the following Content Security Policy directive: "default-src https:". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

So what I've done: In index.html, I've set:

<meta http-equiv="Content-Security-Policy"
      content="default-src https: http:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https: http:; style-src http: https: 'unsafe-inline'; img-src 'self' data: https:; connect-src http: https: ws:;">

In a manual Spring filter, I've set:

httpServletResponse.setHeader("Content-Security-Policy",
                                  "default-src https: http:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https: http:; style-src http: https: 'unsafe-inline'; img-src 'self' data: https:; connect-src http: https: ws:;");

But of course, this has no effect, because I'm not calling the API for the html/js/css.

As I understand, this is not meant to be configured on Tomcat. Where do you normally configure Content Security Policy / Content-Security-Policy headers?

I need a solution that does not need manual configuration on the server where the files will be installed.

Thanks in advance!


回答1:


Spring Security allows users to easily inject security headers to assist in protecting their application. Here is the Spring Security Reference Document for content security policy. It’s important to note that Spring Security does not add Content Security Policy by default. The web application author must declare the security policy(s) to enforce and/or monitor for the protected resources. You can enable the CSP header using Java configuration as shown below:

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    // ...
    .headers()
        .contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/");
}
}


来源:https://stackoverflow.com/questions/42444106/where-should-you-configure-content-security-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!