Spring

Spring 5.3 이상에서 Stomp 및 SockJS로 CORS 오리진을 처리하는 방법은 무엇입니까?

기록만이살길 2022. 12. 7. 13:11
반응형

Spring 5.3 이상에서 Stomp 및 SockJS로 CORS 오리진을 처리하는 방법은 무엇입니까?

1. 질문(문제점):

REST Endpoints과 SockJS websocket을 모두 사용하는 서버 응용 프로그램에서 작업하고 있습니다. 이것은 Spring 5.2 이하에서 잘 작동했습니다.

그러나 5.3 릴리스 이후 에는 다음과 같은 방법이 있습니다 org.springframework.web.cors.CorsConfiguration.

    public void validateAllowCredentials() {
        if (this.allowCredentials == Boolean.TRUE &&
                this.allowedOrigins != null && this.allowedOrigins.contains(ALL)) {

            throw new IllegalArgumentException(
                    "When allowCredentials is true, allowedOrigins cannot contain the special value \"*\"" +
                            "since that cannot be set on the \"Access-Control-Allow-Origin\" response header. " +
                            "To allow credentials to a set of origins, list them explicitly " +
                            "or consider using \"allowedOriginPatterns\" instead.");
        }
    }

지금까지 내 소켓은 다음과 같이 구성되었습니다.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // prefix for the client to send messages to the server
        config.setApplicationDestinationPrefixes("/app");
        // prefix for the client to receive broadcasted messages from the server
        config.enableSimpleBroker("/topic");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // defines the url of the socket so the client can connect to it
        registry.addEndpoint("/socketendpoint").setAllowedOrigins("*").withSockJS();
    }
} 

이제 실제 문제에 직면했습니다.

  • 를 에 유지하면 setAllowedOrigins("*")WebSocketConfiguration오류가 발생합니다 validateAllowCredentials.
  • 를 제거하면 setAllowedOrigins("*")SockJS 클라이언트는 Error during WebSocket handshake: Unexpected response code: 403.

컴파일 타임에 원본 도메인을 모릅니다.

나는 이미 Cors Filter와 Cors Configuration을 사용하여 "return the originheader you find in the request allow-origin" 패턴을 사용하여 일반적으로 우회하는 데 사용되는 패턴을 allow-origin: "*"시도했지만 일부 SockJS 요청에는 origin헤더가 할당되지 않았습니다...

이 문제를 어떻게 해결합니까?

2. 해결방안:

향후 참조를 위해 최신 Spring 업데이트를 통해 이제 이를 해결하는 방법 setAllowedOriginPatterns이 있습니다.

 registry.addEndpoint("/socketendpoint").setAllowedOriginPatterns("*").withSockJS();
반응형