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

前端 未结 2 705
梦毁少年i
梦毁少年i 2020-12-13 03:14

I\'m developing a realtime notification system in Spring 4 by using a build-in Message Broker, and STOMP over WebS

相关标签:
2条回答
  • 2020-12-13 03:44

    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.

    0 讨论(0)
  • 2020-12-13 03:57

    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

    0 讨论(0)
提交回复
热议问题