2017-06-30 33 views
0

AbstractWebSocketMessageBrokerConfigurer(Spring Boot)有没有办法拦截用户注册到特定渠道?STOMP的Spring MVC Websockets - 针对特定渠道进行身份验证

我有使用HandshakeHandler在registerStompEndpoints一个基本的身份验证完成:

@Override 
public void registerStompEndpoints(StompEndpointRegistry registry) { 
    HandshakeHandler handler = new DefaultHandshakeHandler() { 
     @Override 
     protected Principal determineUser(ServerHttpRequest request, 
      WebSocketHandler wsHandler, Map<String, Object> attributes) { 
     Principal principal = request.getPrincipal(); 
     if (principal == null) { 
     return() -> getPrincipal(); 
     } 
     return principal; 
    } 
    }; 
    registry.addEndpoint("/websocket") 
    .setHandshakeHandler(handler) 
    .setAllowedOrigins("*").withSockJS(); 
} 

现在我想阻止这个用户从注册到“/主题/管理/新闻”,如果用户没有权限“管理员”。我没有使用Spring Security。我想在注册频道之前有一个拦截器。

作为一种替代方法,我想使用SimpMessagingTemplate仅向具有权限的频道的用户发送消息。有没有办法查看哪些用户目前连接到我的stomp连接?

回答

1
public void configureClientInboundChannel(ChannelRegistration registration) { 
    registration.setInterceptors(new TopicSubscriptionInterceptor()); 
} 

而且拦截:

public class TopicSubscriptionInterceptor implements ChannelInterceptor { 

private static Logger logger = org.slf4j.LoggerFactory.getLogger(TopicSubscriptionInterceptor.class); 

@Override 
public Message<?> postReceive(Message<?> message, MessageChannel chanenel) { 
    return message; 
} 

@Override 
public void postSend(Message<?> message, MessageChannel chanel, boolean sent) { 
} 

@Override 
public boolean preReceive(MessageChannel channel) { 
    return true; 
} 

@Override 
public Message<?> preSend(Message<?> message, MessageChannel channel) { 
    StompHeaderAccessor headerAccessor= StompHeaderAccessor.wrap(message); 
    if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand()) && headerAccessor.getHeader("simpUser") !=null && headerAccessor.getHeader("simpUser") instanceof UsernamePasswordAuthenticationToken) { 
     UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) headerAccessor.getHeader("simpUser"); 
     if(!validateSubscription((User)userToken.getPrincipal(), headerAccessor.getDestination())) 
     { 
      throw new IllegalArgumentException("No permission for this topic"); 
     } 
    } 
    return message; 
} 

private boolean validateSubscription(User principal, String topicDestination) 
{ 
    logger.debug("Validate subscription for {} to topic {}",principal.getUsername(),topicDestination); 
    //Validation logic coming here 
    return true; 
} 
} 
+0

正是我一直在寻找。干杯。 – Frame91

相关问题