Search code examples
javaspringspring-bootspring-websocket

How to get websocket session on service?


I have a service called UserMediator that has a method to retrieve all users on the database that the session user has access.

@Service
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserMediator {

    @Autowired
    private UserService userSerivce;

    pulibc Collection<User> getAllUsers() {
        Session session = someMethodToGetTheCurrentSessionFromThisService();
        return userService.getAllUsersThatYouAreAllowedToSee(session);
    }

}

I know that, using websocket scope, one instance of this service will be created for each websocket session, so, there must be a way to retrieve the session that created this bean, i think.

One way to do that is to redefine getAllUsers() to getAllUsers(StompHeaderAcessor ha) and get the session using this header acessor, but this not seems to be the proper solution for me.

Is there any way to get the current websocket session in a websocket scoped service without passing it explicity by arguments?


Solution

  • Solved this issue by creating a SessionHolder service:

    @Service
    @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public class SessionHolder {
    
        private User user = null;
    
        @Autowired
        public SessionHolder(SimpMessagingTemplate template) {
            this.template = template;
        }
    
        @EventListener(SessionConnectedEvent.class)
        public void handleSessionConnected(SessionConnectedEvent event) {
            if (user == null && event.getUser() != null) {
                StompHeaderAccessor ha = StompHeaderAccessor.wrap(event.getMessage());
                user = SessionUtils.getUser(ha);
            }
        }
    
        public User getUser() {
            return user;
        }
    
    }