【发布时间】:2021-03-15 16:02:14
【问题描述】:
我正在开发一个同时使用 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();
}
}
现在我面临一个真正的问题:
- 如果我将
setAllowedOrigins("*")保留在WebSocketConfiguration中,那么我将面临validateAllowCredentials中抛出的错误。 - 如果我删除
setAllowedOrigins("*"),那么 SockJS 客户端将收到Error during WebSocket handshake: Unexpected response code: 403。
我在编译时不知道源域。
我已经尝试了一个 Cors 过滤器和一个 Cors 配置,它们使用典型的“将您在请求中找到的 origin 标头返回为 allow-origin”模式,该模式通常用于规避 allow-origin: "*",但一些 SockJS 请求没有分配origin 标头...
我该如何解决这个问题?
【问题讨论】:
-
对于没有 Origin 请求标头的请求,不要在响应中发送 Access-Control-Allow-Origin 标头,因为无论这些请求来自哪里,它们re 不是来自将在响应中查找 Access-Control-Allow-Origin 标头的浏览器。唯一对 Access-Control-Allow-Origin 标头有任何用途的用户代理,甚至浏览器也只关心它只对浏览器本身添加了 Origin 标头的请求的响应。因此,任何缺少 Origin 标头的请求都不需要响应中的 Access-Control-Allow-Origin。
-
你能找到解决办法吗?
-
我们选择延迟依赖升级。 Spring 存储库最近已经提交了关于此问题的提交,它应该包含在即将发布的版本之一中;不知道它是否已经出来了。
标签: java spring websocket cors sockjs