使用远程SSO服务器保护Spring WebSocket的安全

时间:2018-09-17 10:48:35

标签: java spring-boot websocket oauth-2.0 single-sign-on

我正在使用微服务架构,所以我有一个单独的SSO服务,可以处理所有身份验证和授权请求。

我在其他服务中使用spring websockets,我需要使用SSO处理的令牌来保护它,因此我添加了此配置来保护websockets。

@Configuration
@EnableResourceServer
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
            .nullDestMatcher().authenticated()
            .simpTypeMatchers(CONNECT).authenticated()
            .simpDestMatchers("/ws/**").hasRole("USER")
            .simpSubscribeDestMatchers("/ws/**").hasRole("USER")
            .anyMessage().denyAll();
}

@Override
protected boolean sameOriginDisabled() {
    return true;
}

}

对于websocket配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/ws/topic");
    config.setApplicationDestinationPrefixes("/ws/view");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/socket/").withSockJS();
}
}

对于远程SSO服务器

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll()
            .antMatchers("/api/**").access("#oauth2.hasScope('service-name')");
    http.csrf().disable();
    http.httpBasic().disable();
}

@Bean
@Primary
@RefreshScope
public CachedRemoteTokenService tokenServices() {
    final CachedRemoteTokenService remoteTokenServices = new CachedRemoteTokenService();
    remoteTokenServices.setCheckTokenEndpointUrl(getCheckTokenEndPointUrl());
    remoteTokenServices.setClientId(getClientId());
    remoteTokenServices.setClientSecret(getClientSecret());
    return remoteTokenServices;
}

我在客户端中添加了令牌,但是它抛出AccessDeniedException

var headers = {
    Authorization: 'Bearer ' + myToken
}
stompClient.send("/ws/view/update/", headers, JSON.stringify(view));

我检查了SSO服务器日志,发现它根本没有调用它!缺少什么吗?

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我使用了本教程,它对我有用。您可以执行以下步骤:Intro to Security and WebSockets