Search code examples
javaspringspring-securityspring-websocket

How to send websocket message to concrete user?


I have following code on server side:

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

@MessageMapping("/hello")
public void greeting(@Payload HelloMessage message, Principal principal) throws Exception {
    Thread.sleep(1000); // simulated delay
    simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/topic/greetings", new Greeting("Ololo"));        
}

client side code:

function connect() {
    var socket = new SockJS('/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}
function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

My actions:

I run application, log in as user1 and initiate message sending from client to server and I see that method greeting is invokes and line simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/topic/greetings", new Greeting("Ololo")) executes successfully but I don't see that message on the client side.

How can I

more sources:

spring security configuration:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String SECURE_ADMIN_PASSWORD = "rockandroll";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .formLogin()
                .loginPage("/index.html")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/sender.html")
                    .permitAll()
                .and()
                .logout()
                    .logoutSuccessUrl("/index.html")
                    .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/js/**", "/lib/**", "/images/**", "/css/**", "/index.html", "/","/*.css","/webjars/**", "/*.js").permitAll()
                .antMatchers("/websocket").hasRole("ADMIN")
                .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
                .anyRequest().authenticated();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(new AuthenticationProvider() {

            @Override
            public boolean supports(Class<?> authentication) {
                return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
            }

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

                List<GrantedAuthority> authorities = SECURE_ADMIN_PASSWORD.equals(token.getCredentials()) ?
                        AuthorityUtils.createAuthorityList("ROLE_ADMIN") : null;

                return new UsernamePasswordAuthenticationToken(token.getName(), token.getCredentials(), authorities);
            }
        });
    }
}

web socket config:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

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

}

update

After advices and reading topic Sending message to specific user on Spring Websocket I tried following:

1.

server side:

simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));

client side:

stompClient.subscribe('/user1/queue/greetings', function(menuItem){
    alert(menuItem);
});

2.

server side:

simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));

client side:

stompClient.subscribe('/user/queue/greetings', function(menuItem){
    alert(menuItem);
});

3.

server side:

simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));

client side:

stompClient.subscribe('user/user1/queue/greetings', function(menuItem){
    alert(menuItem);
});

It doesn't work anyway


Solution

  • Only necessary change is on the client (app.js): Instead of /user/user1/queue/greetings, subscribe to /user/queue/greetings:

    stompClient.subscribe('/user/queue/greetings', ...
    

    Then login as user1 in the web interface. It has to be user1 because that's the user that is targeted at the server:

    convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo")) 
    

    Upon clicking Send, The Ololo message appears as a client alert.