如何在Spring5.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("*")inWebSocketConfiguration,那么我将面临抛出的错误validateAllowCredentials。 - 如果我删除
setAllowedOrigins("*"),那么 SockJS 客户端将收到一个Error during WebSocket handshake: Unexpected response code: 403.
我在编译时不知道原始域。
我已经尝试了 Cors 过滤器和 Cors 配置,它们使用典型的“将origin您在请求中找到的标头返回为allow-origin”模式,通常用于规避allow-origin: "*",但某些 SockJS 请求没有origin分配标头...
我该如何解决?
回答
为了将来参考,随着最新的 spring 更新,现在有一种方法setAllowedOriginPatterns可以解决这个问题:
registry.addEndpoint("/socketendpoint").setAllowedOriginPatterns("*").withSockJS();
- For me, it fixes the error but I simply don't receive any message of my other Spring application anymore. It sends a message but nothing is received. And it worked with earlier Spring Boot versions (2.2 and earlier)
THE END
二维码