首页 > 解决方案 > 如何在 Spring 5.3 及更高版本中使用 Stomp 和 SockJS 处理 CORS 起源?

问题描述

我正在开发一个同时使用 REST 端点和 SockJS websocket 的服务器应用程序。这曾经在 Spring 5.2 及更低版本下运行良好。

但是,从 5.3 版本开始,以下方法存在于org.springframework.web.cors.CorsConfiguration

    public void validateAllowCredentials() {
        if (this.allowCredentials == Boolean.TRUE &&
                this.allowedOrigins != null && this.allowedOrigins.contains(ALL)) {

            throw new IllegalArgumentException(
                    "When allowCredentials is true, allowedOrigins cannot contain the special value \"*\"" +
                            "since that cannot be set on the \"Access-Control-Allow-Origin\" response header. " +
                            "To allow credentials to a set of origins, list them explicitly " +
                            "or consider using \"allowedOriginPatterns\" instead.");
        }
    }

到目前为止,我的套接字配置如下:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // prefix for the client to send messages to the server
        config.setApplicationDestinationPrefixes("/app");
        // prefix for the client to receive broadcasted messages from the server
        config.enableSimpleBroker("/topic");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // defines the url of the socket so the client can connect to it
        registry.addEndpoint("/socketendpoint").setAllowedOrigins("*").withSockJS();
    }
} 

现在我面临一个真正的问题:

我在编译时不知道源域。

origin我已经尝试过使用典型的“将您在请求中找到的标头作为”模式的 Cors 过滤器和 Cors 配置,该模式allow-origin通常用于规避.allow-origin: "*"origin

我该如何解决?

标签: javaspringwebsocketcorssockjs

解决方案


为了将来参考,随着最新的春季更新,现在有一种方法setAllowedOriginPatterns可以解决这个问题:

 registry.addEndpoint("/socketendpoint").setAllowedOriginPatterns("*").withSockJS();

推荐阅读