我正在实现一个股票应用程序的版本,其中服务器能够根据用户权限拒绝某些主题的主题订阅。spring中有没有一种方法可以做到这一点--websocket?
例如:
在股票示例项目中,我们有3个工具的价格主题:苹果、微软、谷歌,并且有两个用户: User1、User2
User1应该可以访问苹果,而微软的User2应该只能访问谷歌
如果User1订阅了谷歌,他应该得到拒绝响应,消息不应该广播给他。
发布于 2014-02-05 22:50:38
多亏了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;
}}
发布于 2018-11-05 18:44:24
在Spring5.x中,如果要扩展AbstractSecurityWebSocketMessageBrokerConfigurer,可以重写以附加拦截器的正确方法是customizeClientInboundChannel
@Override
public void customizeClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new TopicSubscriptionInterceptor());
}https://stackoverflow.com/questions/21554230
复制相似问题