Spring websocket security for multiple users

人走茶凉 提交于 2019-12-06 06:51:49

Spring WebSocket handles /user channel, so I used those methods

This is how I solved this problem:

When user authenticates with Spring Security, WebSocket module creates unique channel for that user based on his Principal. Example "/user/queue/position-updates" is translated to "/queue/position-updates-user123"

So on the client side all I had to do, was subscribe to /user/queue/requests

And on the server side, send messages to /user/{username}/queue/requests with convertAndSendToUser(request.getFromUser(), "/queue/requests", request) and Spring handles the rest.

You can do something as follows given in Spring-websocket-chat. At client side you can have /app/chat.private.{targetUser}

At Server side you can get target user by using @DestinationVariable and source user from Principal

@MessageMapping("/chat.private.{username}")
    public void filterPrivateMessage(@Payload ChatMessage message, @DestinationVariable("username") String username, Principal principal) {
        checkProfanityAndSanitize(message);

        message.setUsername(principal.getName());

        simpMessagingTemplate.convertAndSend("/user/" + username + "/queue/chat.message", message);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!