ythy / blog

Give everything a shot
6 stars 0 forks source link

Spring Websocket cros #209

Open ythy opened 5 years ago

ythy commented 5 years ago

without stomp

Configuring allowed origins

As of Spring Framework 4.1.5, the default behavior for WebSocket and SockJS is to accept only same origin requests. It is also possible to allow all or a specified list of origins. This check is mostly designed for browser clients. The 3 possible behaviors are:

  1. Allow only same origin requests (default): in this mode, when SockJS is enabled, the Iframe HTTP response header X-Frame-Options is set to SAMEORIGIN, and JSONP transport is disabled since it does not allow to check the origin of a request. As a consequence, IE6 and IE7 are not supported when this mode is enabled.
  2. Allow a specified list of origins: each provided allowed origin must start with http:// or https://. In this mode, when SockJS is enabled, both IFrame and JSONP based transports are disabled. As a consequence, IE6 through IE9 are not supported when this mode is enabled.
  3. Allow all origins: to enable this mode, you should provide * as the allowed origin value. In this mode, all transports are available. WebSocket and SockJS allowed origins can be configured as shown bellow:
    
    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(), "/myHandler").setAllowedOrigins("http://mydomain.com");
}

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

}

## Use SockJS
###  error 1

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'.

正确设置应如下 : 
```kotlin
@EnableWebSecurity
class WebSecurityConfig : WebSecurityConfigurerAdapter() {

    @Override
    override fun configure(http: HttpSecurity){
        http.cors().and()
    }

    @Bean
    fun corsConfigurationSource(): CorsConfigurationSource {
        val configuration = CorsConfiguration()
        configuration.allowedOrigins = mutableListOf("http://127.0.0.1:8118", "http://127.0.0.1:9081")
        configuration.allowedMethods = mutableListOf("GET", "POST")
        configuration.allowCredentials = true
        val source = UrlBasedCorsConfigurationSource()
        source.registerCorsConfiguration("/**", configuration)
        return source
    }
}

@Configuration
@EnableWebSocketMessageBroker
class WebSocketBrokerConfig : WebSocketMessageBrokerConfigurer {
    override fun registerStompEndpoints(registry: StompEndpointRegistry) {
        registry.addEndpoint("/chat-stomp").setAllowedOrigins("http://127.0.0.1:9081").withSockJS()
    }
}

configuration.allowedOrigins 这里不能设置为 “*” egistry.addEndpoint("/chat-stomp").setAllowedOrigins("http://127.0.0.1:9081"). 必需

error2

configuration.allowCredentials = true 这个选项要设置为 true

Request.credentials

The credentials read-only property of the Request interface indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.

Access-Control-Allow-Credentials

The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend JavaScript code when the request's credentials mode (Request.credentials) is "include".

ythy commented 5 years ago

注意: 客户端应当先订阅消息, 然后发消息, 否则由于时间差,会收不到服务器反馈的消息