2017-07-14 18 views
1

私は@SubscribeMappingをSpring Bootアプリケーションで使用します。これは、データ交換のためにWebSocketsに大きく依存しています。アプリケーションはSpring Securityで保護されています。私はWebSocketの上でストンプを使用現在のユーザーをSpring @SubscribeMappingで取得する

クライアント側:

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も参考になる場合があります。

関連する問題