4

I use @SubscribeMapping in a Spring Boot application which heavily relies on WebSockets for data exchange. The application is secured with Spring Security.

Client-side I use Stomp over WebSocket:

this.socket = new WebSocket(this.socketUrl);
this.stompClient = Stomp.over(this.socket);
this.stompClient.debug = null;
this.stompClient.connect({},
    function(frame) {
        this.$.chartLoader.generateRequest();
    }.bind(this),
    function(e) {
        window.setTimeout(function() {
            this.connectWs();
        }.bind(this), 2500);
    }.bind(this)
);

this.stompClient.subscribe('/topic/chart/' + chart.id,
    function(message, headers) {
        this.setChartData(chart, JSON.parse(message.body));
    }.bind(this), {
        "id" : "" + chart.id
    }
);

Server-side, how can I get the currently logged user in the annotated methods ?

@SubscribeMapping("/chart/{id}")
public void subscribeMapping(@DestinationVariable("id") final short id) {
    // Here I would need the current user...
    messagingTemplate.convertAndSend("/topic/chart/" + id, chartService.getChartData(account, sensor, new Date(), new Date()));
}

I have tried SecurityContextHolder.getContext().getAuthentication(), but it returns null.

1 Answer 1

4

You can try to add a Principal object as a method parameter. This interface is extended by Authentication which has several implementations available (Spring will inject the good one according to your configuration).

public void subscribeMapping(@DestinationVariable("id") final short id, Principal principal) {
   principal.getName();    
}

This article may also help you.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.