内容安全策略:页面的设置阻止了加载

Content Security Policy: The page’s settings blocked the loading

我在我的本地服务器中使用 WebSocket (wss://),它与 :

一起工作正常

但是当将该程序部署到将 nginx 配置为反向代理和有效 ssl(certbor,让我们加密)的服务器时,我的程序无法正常工作,并且在 java 脚本客户端和我在那里写的一些细节中出现此错误:

浏览器控制台错误:

Content Security Policy: The page’s settings blocked the loading of a resource at ws:/// (“default-src”).

Java 错误指向的脚本代码:

var ws = new WebSocket('wss://' + location.host + '/<some-url>');

Nginx 配置:

user nginx;
worker_processes 1;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {

   include /etc/nginx/conf-enabled/*.conf;
   include /etc/nginx/sites-enabled/*.conf;


    server {
          listen       443;
          listen [::]:443 ;

          server_name  www.<my-domain> <my-domain>;

          location / {
            proxy_pass       http://127.0.0.1:<my-port>/;
            proxy_redirect off;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_pass_request_headers on;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
          }

          ssl_certificate /etc/letsencrypt/live/<my-domain>/fullchain.pem; # managed by Certbot
          ssl_certificate_key /etc/letsencrypt/live/<my-domain>/privkey.pem; # managed by Certbot
          include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
          ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    }



}

有2点:

  1. 您有生产服务器某处发布的 CSP headers。 Spring Security 默认不添加 Content Security Policy,Nginx 可以这样做,我在它的配置中没有看到类似的东西:add_header Content-Security-Policy "default-src 'self'";
    无论如何,检查 servlet-headers-csp 是不是这样:

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) {
http
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'")
)
);
}
}

或:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers()
            .contentSecurityPolicy("default-src 'self'");
    }
}

确保 'self' 存在或将 ws: 添加到现有规则。在 https: pages 'self' 上是阴险的——它只允许 https: 和 wss:(而不是 http: 和 ws:——无论如何这些都会被作为混合内容阻止)。在 http: 页面 'self' 允许 https: / wss: / http: / ws:.
向您的 CSP 添加特定的 connect-src 'self'connect-src ws://site.com wss:site.com 指令可能更好。
如果不需要CSP,去掉相关即可:

http.headers()
  .contentSecurityPolicy("default-src 'self'");
  1. In err: blocked the loading of a resource at ws:/// - ws:/// 意味着在 new WebSocket('wss://' + location.host + '/<some-url>') location.host 中是空的,所以 websocket 没有连接的地方。任何 CSP 都会阻止 ws:/// 源无效。