복붙노트

[SPRING] Spring-websocket을 이용한 사용자 권한 기반의 토픽 구독 거부 방법

SPRING

Spring-websocket을 이용한 사용자 권한 기반의 토픽 구독 거부 방법

서버가 사용자 권한에 따라 특정 주제에 대한 주제 가입을 거부 할 수있는 주식 애플리케이션 버전을 구현하고 있습니다. Spring-websocket에서이 작업을 수행 할 수있는 방법이 있습니까?

예 :

주식 예를 들어 우리는 3 가지 악기 (Apple, Microsoft, Google)에 대한 가격 주제를 가지고 있습니다. 그리고 두 명의 사용자가 있습니다 : User1, User2

User1은 Apple과 Microsoft에 액세스해야합니다. User2는 Google에만 액세스 할 수 있어야합니다.

User1이 Google에 가입하면 거부 된 응답을 받아야하며 이후에는 메시지가 전송되지 않아야합니다.

해결법

  1. ==============================

    1.github에 대한 Rossen Stoyanchev의 답변 덕분에 인바운드 채널에 인터셉터를 추가하여이를 해결할 수있었습니다. spring-websocket-portfolio 데모 애플리케이션에 필요한 변경 사항은 다음과 같습니다.

    github에 대한 Rossen Stoyanchev의 답변 덕분에 인바운드 채널에 인터셉터를 추가하여이를 해결할 수있었습니다. 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;
    }
    

    }

  2. ==============================

    2.Spring 5.x에서 AbstractSecurityWebSocketMessageBrokerConfigurer를 확장하는 경우 인터셉터를 부착하기위한 올바른 방법은 customizeClientInboundChannel입니다.

    Spring 5.x에서 AbstractSecurityWebSocketMessageBrokerConfigurer를 확장하는 경우 인터셉터를 부착하기위한 올바른 방법은 customizeClientInboundChannel입니다.

    @보수 public void customizeClientInboundChannel (채널 등록 등록) {     registration.interceptors (새로운 TopicSubscriptionInterceptor ()); }

  3. from https://stackoverflow.com/questions/21554230/how-to-reject-topic-subscription-based-on-user-rights-with-spring-websocket by cc-by-sa and MIT license