Check auth while sending a message to a specific user by using STOMP and WebSocket in Spring

馋奶兔 提交于 2019-11-28 17:20:26

I found the solution.

First of all, it is important to know that the /user channel is already managed by Spring STOMP, and by the way, no registration is required.

So:

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic", "/queue");
}

Then, I setup the destination channel as /queue/horray:

@Scheduled(fixedDelay=5000)
public void sendMessages(Principal principal)
    messagingTemplate
        .convertAndSendToUser(principal.getName(), "/queue/horray", "Horray, " + principal.getName() + "!");
}

At last, on client:

stompClient.subscribe('/user/queue/horray', '...');

Now, it works fine! Messages are sent only to the specified recipient, according to the Principal fetched by the security context.

Since users on my application are not authenticated I just used the session Id to differenciate the various topics

on the server:

template.convertAndSend("/topic/warnings/" + sessionId, ...)

And the client is pretty straightforward

stompClient.subscribe('/topic/warnings/${pageContext.session.id}', ...

Maybe not the cleanest way but it works, and without authentication I couldn't make use of /user channel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!