我正在开发一个服务器应用程序,它同时使用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();
}
}
现在我面临一个真正的问题:
- 如果我在
WebSocketConfiguration
中保留setAllowedOrigins("*")
,那么我将面对在validateAllowCredentials
中抛出的错误。 - 如果我删除
setAllowedOrigins("*")
,那么SockJS客户端将收到一个Error during WebSocket handshake: Unexpected response code: 403
。
我不知道原始域名在编译时是什么。
我已经尝试了一个Cors Filter和一个Cors Configuration,它们使用典型的“返回在请求中找到的origin
头作为allow-origin
”模式来规避allow-origin:"*"
,但有些SockJS请求没有分配origin
头...
我该如何解决这个问题?