我正在实现一个版本的股票应用程序,其中服务器能够根据用户权限拒绝特定主题的主题订阅。 spring-websocket有没有办法做到这一点?
例如:
在股票示例项目中,我们有3种工具的价格主题:Apple,Microsoft,Google 并有两个用户:User1,User2
User1应该可以访问Apple和Microsoft User2应该只能访问Google
如果User1订阅Google,他应该被拒绝回复,之后不应该向他广播。
答案 0 :(得分:41)
感谢Rossen Stoyanchev answer on github我设法通过向入站通道添加拦截器来解决这个问题。 spring-websocket-portfolio演示应用程序中所需的更改如下:
更改websocket配置:
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(new TopicSubscriptionInterceptor());
}
拦截器是这样的:
public class TopicSubscriptionInterceptor extends ChannelInterceptorAdapter {
private static Logger logger = org.slf4j.LoggerFactory.getLogger(TopicSubscriptionInterceptor.class);
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor headerAccessor= StompHeaderAccessor.wrap(message);
if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand())) {
Principal userPrincipal = headerAccessor.getUser();
if(!validateSubscription(userPrincipal, headerAccessor.getDestination()))
{
throw new IllegalArgumentException("No permission for this topic");
}
}
return message;
}
private boolean validateSubscription(Principal principal, String topicDestination)
{
if (principal == null) {
// unauthenticated user
return false;
}
logger.debug("Validate subscription for {} to topic {}",principal.getName(),topicDestination);
//Additional validation logic coming here
return true;
}
}
答案 1 :(得分:2)
从Spring 5.x开始,如果要扩展AbstractSecurityWebSocketMessageBrokerConfigurer
,重写覆盖侦听器的正确方法是customizeClientInboundChannel
:
@Override
public void customizeClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new TopicSubscriptionInterceptor());
}