Java – spring websocket sent to specific people
I added custom token based authentication for spring web app and extended the same authentication for spring websocket, as shown below
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic","/queue");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(new ChannelInterceptorAdapter() {
@Override
public Message<?> preSend(Message<?> message,MessageChannel channel) {
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message,StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
String jwtToken = accessor.getFirstNativeHeader("Auth-Token");
if (!StringUtils.isEmpty(jwtToken)) {
Authentication auth = tokenService.retrieveUserAuthToken(jwtToken);
SecurityContextHolder.getContext().setAuthentication(auth);
accessor.setUser(auth);
//for Auth-Token '12345token' the user name is 'user1' as auth.getName() returns 'user1'
}
}
return message;
}
});
}
}
The client code to connect to the socket is
var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({'Auth-Token': '12345token'},function (frame) {
stompClient.subscribe('/user/queue/greetings',function (greeting) {
alert(greeting.body);
});
});
Send me a message from my controller as
messagingTemplate.convertAndSendToUser("user1","/queue/greetings","Hi User1");
For auth token 12345 token, the user name is user1 But when I sent a message to user1, it didn't receive it on the client Is there anything I miss?
Solution
In your websocket controller, you should do the following:
@Controller
public class GreetingController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@MessageMapping("/hello")
public void greeting(Principal principal,HelloMessage message) throws Exception {
Greeting greeting = new Greeting();
greeting.setContent("Hello!");
messagingTemplate.convertAndSendToUser(message.getToUser(),"/queue/reply",greeting);
}
}
On the client side, your users should subscribe to topic / user / queue / reply
You must also add some destination prefixes:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic","/queue","/user");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
/*...*/
}
When your server receives messages on the / APP / Hello queue, it should send messages to users in your dto The user must be equal to the principal of the user
I think the only problem in your code is that your "/ user" is not in your target prefix Your greeting messages are blocked because you sent them to a queue starting with / user and did not register this prefix
You can view the source on git repo: https://github.com/simvetanylen/test-spring-websocket
I hope it works!
