【问题标题】:Enabling Cross Origin Requests for WebSockets in Spring在 Spring 中为 WebSockets 启用跨域请求
【发布时间】:2017-02-02 15:07:04
【问题描述】:

我有一个 OpenShift Wildfly 服务器。我正在使用Spring MVC 框架构建一个网站。我的一个网页也使用了 WebSocket 连接。在服务器端,我使用了@ServerEndpoint 注释和javax.websocket.* 库来创建我的websocket:

package com.myapp.spring.web.controller;
import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.socket.server.standard.SpringConfigurator;


@ServerEndpoint(value="/serverendpoint", configurator = SpringConfigurator.class)

public class serverendpoint {

    @OnOpen
    public void handleOpen () {
        System.out.println("JAVA: Client is now connected...");
    }

    @OnMessage
    public String handleMessage (Session session, String message) throws IOException {

        if (message.equals("ping")) {
//            return "pong"
                session.getBasicRemote().sendText("pong");
        }
        else if (message.equals("close")) {
            handleClose();
            return null;
        }
        System.out.println("JAVA: Received from client: "+ message);
        MyClass mc = new MyClass(message);
        String res = mc.action();
        session.getBasicRemote().sendText(res);
        return res;
    }

    @OnClose
    public void handleClose() {
        System.out.println("JAVA: Client is now disconnected...");
    }

    @OnError
    public void handleError (Throwable t) {
        t.printStackTrace();
    }
}

OpenShift 提供了一个默认 URL,因此我的所有网页(html 文件)都具有通用(规范)主机名。为简单起见,我将此 URL 称为 URL A (projectname-domainname.rhclound.com)。我创建了URL A 的别名CNAME,称为URL B(比如https://www.mywebsite.tech)。 URL B 是安全的,因为它具有 https

我正在使用 JavaScript 客户端连接到路径 /serverendpoint 的 WebSocket。我在我的 html 网页文件中使用的 URI,test.html,如下:

var wsUri = "wss://" + "projectname-domainname.rhclound.com" + ":8443" + "/serverendpoint";

当我打开 URL A (projectname-domainname.rhclound.com/test) 时,WebSocket 连接并且一切正常。但是,当我尝试使用 URL B (https://mywebsite.tech/test) 连接到 websocket 时,JavaScript 客户端会立即连接和断开连接。

这是我从控制台收到的消息:

这是我连接到 WebSocket 的 JavaScript 代码:

/****** BEGIN WEBSOCKET ******/
            var connectedToWebSocket = false;
            var responseMessage = '';
            var webSocket = null;
            function initWS() {
                connectedToWebSocket = false;
                var wsUri = "wss://" + "projectname-domainname.rhcloud.com" + ":8443" + "/serverendpoint";
                webSocket = new WebSocket(wsUri); // Create a new instance of WebSocket using usUri
                webSocket.onopen = function(message) {
                    processOpen(message);
                };
                webSocket.onmessage = function(message) {
                    responseMessage = message.data;
                    if (responseMessage !== "pong") { // Ping-pong messages to keep a persistent connection between server and client
                        processResponse(responseMessage);
                    }
                    return false;
                };
                webSocket.onclose = function(message) {
                    processClose(message);
                };
                webSocket.onerror = function(message) {
                    processError(message);
                };
                console.log("Exiting initWS()");
            }

            initWS(); //Connect to websocket

            function processOpen(message) {
                connectedToWebSocket = true;
                console.log("JS: Server Connected..."+message);
            }

            function sendMessage(toServer) { // Send message to server
                if (toServer != "close") {
                    webSocket.send(toServer);
                } else {
                    webSocket.close();
                }
            }

            function processClose(message) {
                connectedToWebSocket = false;
                console.log("JS: Client disconnected..."+message);
            }

            function processError(message) { 
                userInfo("An error occurred. Please contact for assistance", true, true);
            }
            setInterval(function() {
                if (connectedToWebSocket) {
                    webSocket.send("ping");
                }
            }, 4000); // Send ping-pong message to server
/****** END WEBSOCKET ******/

经过大量调试和尝试各种事情后,我得出结论,这是由于 Spring 框架而出现的问题。 这是因为在我的项目中引入Spring Framework之前,URL B可以连接WebSocket,但是引入Spring之后就不能了。
我在spring's website 上阅读了有关 WebSocket 策略的信息。我遇到了他们的same origin policy,其中指出别名URL B 无法连接到WebSocket,因为它与URL A 的来源不同。为了解决这个问题我disabled the same origin policy with WebSockets在文档中说,所以我添加了以下代码。我认为这样做可以解决我的错误。这是我添加的内容:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;

@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

    @Override
    protected boolean sameOriginDisabled() {
        return true;
    }

}

但是,这并没有解决问题,所以我将以下方法添加到我的ApplicationConfig 其中extends WebMvcConfigurerAdapter

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("https://www.mywebsite.com");
}

这也不起作用。然后我尝试了这个:

package com.myapp.spring.security.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class MyCorsFilter {

//  @Bean
//  public FilterRegistrationBean corsFilter() {
//      System.out.println("Filchain");
//      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//      CorsConfiguration config = new CorsConfiguration();
//      config.setAllowCredentials(true);
//      config.addAllowedOrigin("https://www.mymt.tech");
//      config.addAllowedHeader("*");
//      config.addAllowedMethod("*");
//      source.registerCorsConfiguration("/**", config);
//      FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//      bean.setOrder(0);
//      System.out.println("Filchain");
//      return bean;
//  }

     @Bean
     public CorsFilter corsFilter() {
         System.out.println("Filchain");
         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
         CorsConfiguration config = new CorsConfiguration();
         config.setAllowCredentials(true); // you USUALLY want this
         config.addAllowedOrigin("*");
         config.addAllowedHeader("*");
         config.addAllowedMethod("*");
         config.addAllowedMethod("*");
         source.registerCorsConfiguration("/**", config);
         System.out.println("Filchain");
         return new CorsFilter(source);
     }

}

这也不起作用。

我什至将 JS 代码中的var wsURI 更改为以下内容: var wsUri = "wss://" + "www.mywebsite.com" + ":8443" + "/serverendpoint"; 然后var wsUri = "wss://" + "mywebsite.com" + ":8443" + "/serverendpoint";

当我这样做时,谷歌浏览器给了我一个错误,说握手失败。但是,当我有这个 URL var wsUri = "wss://" + "projectname-domianname.rhcloud.com" + ":8443" + "/serverendpoint"; 时,我没有收到没有发生握手的错误,而是收到一条消息,表明连接立即打开和关闭(如上所示)。

那么我该如何解决这个问题?

【问题讨论】:

  • 您是否尝试过将 websocket 设置为 url b 本地?只是为了测试它是否完全连接
  • 如果您的后端和前端同时存在,您可以利用代理:这种方式不会发生跨源资源共享。

标签: spring-mvc spring-security spring-boot websocket spring-websocket


【解决方案1】:

您是否尝试过实现WebMvcConfigurer 并覆盖方法addCorsMappings()?如果没有试试这个看看。

@EnableWebMvc
@Configuration
@ComponentScan
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")
        .allowedOrigins("*")
        .allowedMethods("GET", "POST")
        .allowedHeaders("Origin", "Accept", "Content-Type", "Authorization")
        .allowCredentials(true)
        .maxAge(3600);

    }

}

【讨论】:

【解决方案2】:

我认为这不是 CORS 问题,因为它在断开连接之前已成功连接。如果那是 CORS,你甚至无法连接。

我认为这是您的 DNS 和 openshift 之间的通信问题,因为 WebSocket 需要一个持久连接(长寿命),它在客户端和服务器之间保持打开。如果您的 DNS(例如 CloudFlare 或类似的东西)不支持/未配置为使用 WebSocket,客户端将立即断开连接,就像您的问题一样。

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 2017-04-01
    • 2017-03-26
    • 1970-01-01
    • 2017-07-27
    • 2015-04-07
    • 1970-01-01
    • 2010-10-14
    • 2015-10-29
    相关资源
    最近更新 更多