我正在尝试实现WebSockets。我的代码:
在Spring Security中,我允许路径w/e进行身份验证
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf()
.disable()
.authorizeRequests()
.antMatchers("/register","/login","/testAuth","/web","/ws").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
以及针对ws的配置
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WsMessageHandler(), "/ws")
.addInterceptors(new CustomInterceptor())
.setAllowedOrigins("*")
.setHandshakeHandler(new DefaultHandshakeHandler())
.withSockJS();
}
}
`
public class CustomInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
return true;
}
@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, @Nullable Exception e) {
}
}
作为客户端,我使用简单的js代码:
var exampleSocket = new WebSocket("ws://localhost:8080/ws", "protocolOne");
exampleSocket.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
然而我收到错误信息:
这是什么原因?一切都应该是正确的。感谢回答。WebSocket连接到'ws://localhost:8080/ws'失败:WebSocket握手期间出错:意外的响应代码:400