当请求的凭据模式为“包含”时,响应中的标头不得为通配符“*”
我用于我的用户身份验证,只允许登录用户访问Spring(Boot)。此时,我正在创建一个实时消息功能,用户可以使用 和 将消息从客户端 () 发送到 Spring 服务器 (localhost:8081)。Auth0
RestController
Angular 2
localhost:4200
stompjs
sockjs
尝试创建 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 中将允许的源设置为客户端域时,如何解决此问题?
角度 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);
});
});
}
WebSocketConfig
@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();
}
}
本地主机:8081/聊天/信息 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());
}
}
安全配置(暂时允许所有)
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://stackoverflow.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();
}
我可以看到过滤器是通过调试它来调用的,但是即使设置了正确的访问控制-允许-源,错误消息也会不断出现在客户端: