Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
How to prevent subscription to spring socket /queue/private/* destination.

I have an Java socket API application, that handles socket requests from users and sends responses. I have a configurer:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    private static final Logger LOGGER = Logger.getLogger(WebSocketConfig.class);
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/queue");
        config.setApplicationDestinationPrefixes("/server_in");
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }
}

When i send response to user i do the following: this.simpMessagingTemplate.convertAndSend("/queue/private/user_"+secret_key, socketResponse);

On client i have the following code:

   sc.subscribe('/queue/private/user_'+secret_key, function (greeting) {
        console.log(greeting.body);
    });

And the response is handled successfully. But the problem is that some other user can also subscribe to "/queue/private/*" destination and handle private messages.

   sc.subscribe('/queue/private/*', function (greeting) {
        console.log(greeting.body);
    });

How can I privent that behaviour?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

If you want each user to have a socket and only get him messages, what you can do is :

Subscribe as you do to the endPoint but with "/user" infront for example

sc.subscribe('/user/queue/websocket, function (greeting) {
    console.log(greeting.body);
});

and at the server side you should have a rest method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public void test(Principal principal) throws Exception {
    this.template.convertAndSendToUser(principal.getName(), "/queue/click", "");
}

With this every user subscibers to each channel and only the user is notified about, when a rest call is made.

The rest call should be authenticated so the Principal has the username.

The user channel is auto managed from Spring so you have to add it like this.

about 4 years ago · Santiago Trujillo Relatório

0

You can extend ChannelInterceptorAdapter and manage each event individually:

public class AuthorizedChannelInterceptorAdapter extends ChannelInterceptorAdapter {
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel messageChannel) throws AuthenticationException {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT == accessor.getCommand())
            setUserAuthenticationToken(accessor);
        else if (StompCommand.SUBSCRIBE == accessor.getCommand())
            validateSubscription((Authentication) accessor.getUser(), accessor.getDestination());
        return message;
    }

    private void setUserAuthenticationToken(StompHeaderAccessor accessor) {
        String token = accessor.getFirstNativeHeader(HttpHeaders.AUTHORIZATION);
        accessor.setUser(loadAuthentication(token));
    }

    private Authentication loadAuthentication(String token){
        return ....;
    }

    private void validateSubscription(Authentication authentication, String destination) {
        if(...)
           throw new AccessDeniedException("No permission to subscribe to this topic");
    }
}

First of all you will need to store the authentication object provided by the client in connection event. After this, each event sent by the client will have this authentication object set so you can use it to validate if it is authorized to subscribe to a particular channel.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda