Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda