【发布时间】:2021-04-09 18:59:10
【问题描述】:
我正在尝试实现 websocket。我的代码:
在 Spring Security 中,我允许使用身份验证的路径
@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...");
};
但是我收到错误:
到 'ws://localhost:8080/ws' 的 WebSocket 连接失败:期间出错 WebSocket 握手:意外响应代码:400
这是什么原因造成的?一切都应该是正确的。谢谢解答
【问题讨论】:
标签: java spring spring-boot websocket