【发布时间】:2026-02-22 17:40:02
【问题描述】:
我使用Auth0 进行用户身份验证,只允许登录用户访问Spring(引导)RestController。此时,我正在创建一个实时消息功能,用户可以使用stompjs 和sockjs 将消息从Angular 2 客户端(localhost:4200)发送到Spring 服务器(localhost:8081)。
在尝试创建 Stomp 客户端并启动连接时,我收到以下控制台错误:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
在研究了这个问题之后,似乎无法同时设置选项 origins = * 和 credentials = true。当我已经将 WebSocketConfig 中的允许来源设置为客户端域时,如何解决此问题?
Angular 2 组件
connect() {
var socket = new SockJS('http://localhost:8081/chat');
this.stompClient = Stomp.over(socket);
this.stompClient.connect({}, function(result) {
console.log('Connected: ' + result);
this.stompClient.subscribe('/topic/messages', function(message) {
console.log(message);
});
});
}
WebSocket配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").setAllowedOrigins("http://localhost:4200").withSockJS();
}
}
localhost:8081/chat/info?t=1490866768565
{"entropy":-1720701276,"origins":["*:*"],"cookie_needed":true,"websocket":true}
消息控制器
public class MessageController {
@MessageMapping("/chat")
@SendTo("/topic/messages")
public Message send(Message message) throws Exception {
return new Message(message.getFrom(), message.getText());
}
}
SecurityConfig(暂时允许所有)
public class SecurityConfig extends Auth0SecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}
更新
经过更多测试和研究,问题似乎只在使用 Chrome 时发生。问题可能与:https://github.com/sockjs/sockjs-node/issues/177
更新
我像提到的 chsdk 一样创建了 CORSFilter,并使用了 addFilterBefore() 方法:https://*.com/a/40300363/4836952。
@Bean
CORSFilter corsFilter() {
CORSFilter filter = new CORSFilter();
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(corsFilter(), SessionManagementFilter.class).authorizeRequests().anyRequest().permitAll();
http.csrf().disable();
}
我可以通过调试看到过滤器被调用,但即使设置了正确的 Access-Control-Allow-Origin,错误消息仍然出现在客户端:
【问题讨论】:
标签: java spring angular auth0 sockjs