Error in handshake 403
Browser console error prompt
Error during WebSocket handshake: Unexpected response code: 403
Configuration example
Websocket registration
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler, "/test").addInterceptors(new SystemInfoSocketHandshakeInterceptor());
registry.addHandler(socketHandler, "/sockjs/test").addInterceptors(new SystemInfoSocketHandshakeInterceptor())
.withSockJS();
}
Handshake interceptor
@Configuration
public class SystemInfoSocketHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object
> attributes) {
log.info("socket beforeHandshake..");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
log.info("socket beforeHandshake..");
}
}
Client connection
var wsServer = "ws://127.0.0.1:8080";
var webSocket;
if ('WebSocket' in window || 'MozWebSocket' in window) {
webSocket = new WebSocket(wsServer + "/test");
} else {
webSocket = new SockJS(wsServer + "/sockjs/test");
}
webSocket.onerror = function (event) {
console.log("websockt connect error")
};
Analysis
Connection failed
Access interception
Nginx agent
Cross domain
Solution
Connectivity issues
If it’s the connection problem above, generally check whether the configuration is correct
Pay attention to the version
Access interception
In the interceptor, unblock
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
nginx proxy
Configure proxy_set_header Upgrade $http_upgrade
proxy_set_header Connection "upgrade"
proxy_set_header Host $host
Three configurations in nginx header Host $host Three configurations
The full configuration is as follows:
location/{
proxy_pass http://127.0.0.1:8080;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Cross domain
Add setallowedorigins ("*")
to solve cross domain problems
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler, "/test")
.addInterceptors(new SystemInfoSocketHandshakeInterceptor())
.setAllowedOrigins("*");
registry.addHandler(socketHandler, "/sockjs/test")
.addInterceptors(new SystemInfoSocketHandshakeInterceptor())
.setAllowedOrigins("*")
.withSockJS();
}