首页 > 解决方案 > Websocket CORS 配置 Spring boot

问题描述

我正在尝试在 Spring 引导服务器上使用 Websocket。

我想设置 allowedOrigins 以允许来自任何地方的连接,如下所示:

@Configuration @EnableWebSocketclass WSConfig : WebSocketConfigurer {
    override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
        registry.addHandler(ChatHandler(), "/chat").setAllowedOrigins("*").withSockJS()
    }
}

但我收到此错误消息:

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.] with root cause

问题是没有在 WebSocketConfigurer 上设置 allowedOriginPatterns 的方法。所以我不明白我应该如何管理这个。与“访问控制允许来源”相同。

我认为有些东西我误解了,但我不明白。

如果你能帮助我理解!任何帮助表示赞赏:)

标签: springkotlinwebsocketcors

解决方案


已经有人回答了这个问题。我猜你正在使用更新版本的 Spring Boot (>5.3)。他们更改了代码中的某些内容,您必须使用

registry.addHandler(ChatHandler(), "/chat").setAllowedOriginPatterns("*").withSockJS();

只需从.setAllowedOrigins("*")to更改.setAllowedOriginPatterns("*"),您就可以了。

根据这个线程: 如何在 Spring 5.3 及更高版本中使用 Stomp 和 SockJS 处理 CORS 起源?


推荐阅读