简体   繁体   中英

CORS error when proxying websockets in spring boot with nginx

trying to proxy websocket connections in spring boot application with nginx with config (without nginx it works ok)

server {
    listen 80;
    listen [::]:80;

    server_name example.com;

    location / {
        proxy_pass http://localhost:8080/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
}

however getting following error js:

WebSocket connection to 'ws://localhost/gs-guide-websocket/776/ybicrrun/websocket' failed: Error during WebSocket handshake: Unexpected response code: 403

spring:

o.s.web.cors.DefaultCorsProcessor        : Reject: 'http://localhost' origin is not allowed
o.s.web.servlet.DispatcherServlet        : Completed 403 FORBIDDEN, headers={masked}

what is the correct way to proxy web socket connections?

found one way to configure allowed origin in spring :

import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/gs-guide-websocket").setAllowedOrigins("http://localhost");
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new MyHandler();
    }

}

still think this is not a proper way, looking how to fix it on nginx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM