Websocket根据用户权限拒绝主题订阅

Websocket根据用户权限拒绝主题订阅

本文介绍了如何使用Spring-Websocket根据用户权限拒绝主题订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现股票应用程序的版本,在该版本中,服务器能够根据用户权限拒绝某些主题的主题订阅.spring-websocket中有没有办法做到这一点?

I'm implementing a version of the stock application where the server able to reject topic subscription for certain topic based on the user rights.Is there a way in spring-websocket to do this?

例如:

在股票示例项目中,我们有3种工具的价格主题:Apple,Microsoft,Google并有两个用户:User1,User2

In the stock example project we have price topic for 3 instrument: Apple, Microsoft, GoogleAnd have two user: User1, User2

User1应该有权访问Apple和MicrosoftUser2应该只能访问Google

User1 should have access to Apple and MicrosoftUser2 should have access to Google only

如果User1订阅了Google,他应该会被拒绝答复,并且此后不应再向他广播消息.

If User1 subscribe to Google he should got rejected response, and message shouldn't broadcast to him afterwards.

推荐答案

感谢Rossen Stoyanchev 在github上的答案我设法通过将拦截器添加到入站通道来解决此问题. spring-websocket-portfolio 所需的更改演示应用程序如下:

Thanks to Rossen Stoyanchev answer on github I was manage to solve this by adding interceptor to the inbound channel. Changes needed in the spring-websocket-portfolio demo application is the following:

更改websocket配置:

Change websocket configuration:

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;
}

}

这篇关于如何使用Spring-Websocket根据用户权限拒绝主题订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:37