2017-07-14 246 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也可能帮助你。