使用SockJS时,Spring Security OAuth2无法保护WebSocket端点吗?

时间:2019-07-17 14:01:05

标签: java spring-boot spring-security-oauth2 spring-websocket sockjs

我正在春季启动中实现websockets,我想使用OAuth2保护我的websocket端点,但是与SockJS连接时出现问题。似乎完全忽略了我设置的所有OAuth2安全性。

这是我在隐含WebSocketMessageBrokerConfigurer的类中配置脚踏端点的方法:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {  
    registry
        .addEndpoint("/websocket/endpoint")
        .setAllowedOrigins("*")
        .withSockJS();
  }

  @Override
  public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker(...)
    config.setApplicationDestinationPrefixes(...);
    config.setUserDestinationPrefix(...);
  }

...
}

这是我的OAuth2设置:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
    // configure oauth2 filter
    http
        // start chain for restricting access.
        .authorizeRequests()
        // for these paths
        .mvcMatchers("/websocket/endpoint")
        // require user to at least be authenticated (protect with oauth2)
        .authenticated()
        // for any other requests
        .anyRequest()
        // allow everything
        .permitAll();
  }

 ...
}

上面的所有代码正常运行后,下面的代码可以连接到/ websocket / endpoint,而无需为OAuth2进行任何其他设置:

function connect() {
    var socket = new SockJS('/websocket/endpoint');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/publicChatRoom', function (helloMessage) {
            console.log(helloMessage.body);
            showChatMessage(JSON.parse(helloMessage.body).messageContent);
        });
    });
}

我缺少任何配置或东西吗?

0 个答案:

没有答案