Uncaught SecurityError:无法构造'WebSocket':可能无法从通过HTTPS加载的页面启动不安全的WebSocket连接

Tin*_*iny 9 ssl html5 java-ee websocket java-ee-7

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

其他当局也是如此.

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

使用WebSockets时如下(JavaScript),

var ws = new WebSocket("ws://localhost:8181/Context/Push");
Run Code Online (Sandbox Code Playgroud)

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

[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.
Run Code Online (Sandbox Code Playgroud)

<user-data-constraint>完全删除web.xml中的部分后,将运行网页HTTP.在那之后,改变,

var ws = new WebSocket("ws://localhost:8181/Context/Push");
Run Code Online (Sandbox Code Playgroud)

var ws = new WebSocket("ws://localhost:8080/Context/Push");
Run Code Online (Sandbox Code Playgroud)

工作良好.

如何使WebSockets在安全通道上工作?

vto*_*ola 18

试试wss://,这表明你想要一个安全的websocket连接.浏览器将阻止您从安全页面创建不安全的连接,因为它了解自您请求页面以来https://,存在传输安全性要求.

如果您的WebSocket服务器与您的Web服务器一起运行,它可能会使用相同的安全证书,您无需执行任何操作.如果它不起作用,请检查WebSocket服务器文档,了解如何添加证书和启用wss://.