java - 如何在 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();
}
}
现在我面临一个真正的问题:
- 如果我保留在
setAllowedOrigins("*")
中WebSocketConfiguration
,那么我将面临在 中抛出的错误validateAllowCredentials
。 - 如果我删除
setAllowedOrigins("*")
,那么 SockJS 客户端将收到一个Error during WebSocket handshake: Unexpected response code: 403
.
我在编译时不知道源域。
origin
我已经尝试过使用典型的“将您在请求中找到的标头作为”模式的 Cors 过滤器和 Cors 配置,该模式allow-origin
通常用于规避.allow-origin: "*"
origin
我该如何解决?
解决方案
为了将来参考,随着最新的春季更新,现在有一种方法setAllowedOriginPatterns
可以解决这个问题:
registry.addEndpoint("/socketendpoint").setAllowedOriginPatterns("*").withSockJS();
推荐阅读
- javascript - 如何在javascript中编写一个将3的倍数转换为字符串的函数
- python - 如何将 XML 元素的内容作为字符串获取?
- php - 如何删除所有 html 标记但从字符串中保留图像源链接
- algorithm - 所有打开的灯泡都亮起的时刻数
- php - 如何使用 Guzzle 向 Laravel 中的另一个控制器发送请求
- spring-integration - 使用 jdbcPollingChannelAdapter 执行多个查询
- java - 在一种方法中返回基类的各种实现
- javascript - 用javascript读取条形码
- javascript - 我可以同步运行 ytdl getInfo() 吗?
- amazon-web-services - ECS服务“稳定”状态查询