2017-07-14 252 views
1

我在Spring Boot應用程序中使用@SubscribeMapping,該應用程序嚴重依賴於WebSockets進行數據交換。該應用程序使用Spring Security進行保護。使用Spring @SubscribeMapping獲取當前用戶

客戶端我用踐踏過的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 
    } 
); 

服務器端,我怎樣才能在註解的方法當前登錄的用戶?

@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())); 
} 

我已經試過SecurityContextHolder.getContext().getAuthentication(),但它返回null

回答

2

您可以嘗試添加Principal對象作爲方法參數。這個接口被擴展了Authentication,它有幾個可用的實現(Spring會根據你的配置注入好的實現)。

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

This article也可能幫助你。