未捕获的安全错误:无法构造“WebSocket”:不允许从通过HTTPS加载的页面发起不安全的WebSocket连接。

13

我正在使用GlassFish Server 4.1/Java EE 7。在我的web.xml文件中,我提到了以下安全约束。

<security-constraint>
    <display-name>UserConstraint</display-name>
    <web-resource-collection>
        <web-resource-name>Provide a Name</web-resource-name>
        <description/>
        <url-pattern>/admin_side/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <description/>
        <role-name>ROLE_ADMIN</role-name>
    </auth-constraint>
    <user-data-constraint>
        <description/>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

其他机构同样适用上述规定。

由于transport-guarantee被设置为CONFIDENTIAL,与指定URL模式/admin_side/*匹配的网页将在安全通道(HTTPS)上运行。

当如下方式(JavaScript)使用WebSockets时,

var ws = new WebSocket("ws://localhost:8181/Context/Push");

连接无法建立初始握手。浏览器在浏览器控制台上显示以下警告。

[blocked] The page at 'https://localhost:8181/Context/admin_side/Category' was loaded over HTTPS, but ran insecure content from 'ws://localhost:8080/Context/Push': this content should also be loaded over HTTPS.

Uncaught SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

当完全删除 web.xml 中的 <user-data-constraint> 部分后,Web 页面会在 HTTP 上运行。之后,更改

var ws = new WebSocket("ws://localhost:8181/Context/Push");

为了

var ws = new WebSocket("ws://localhost:8080/Context/Push");

运行良好。

如何使WebSockets在安全通道上运行?


1
没错!它起作用了。我以前从未见过 wss://。可以将其添加为答案吗?谢谢。 - Tiny
谢谢!我还添加了一些额外的信息供以后参考。 - vtortola
1个回答

27
尝试使用 wss://,它表示您想要一个安全的 WebSocket 连接。浏览器会阻止您从安全页面创建不安全的连接,因为它知道由于您以 https:// 请求页面,存在传输安全性要求。
如果您的 WebSocket 服务器与 Web 服务器一起运行,它可能会使用相同的安全证书,您无需进行任何操作。如果无法正常工作,请检查您的 WebSocket 服务器文档,了解如何添加证书并启用 wss://

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接