【问题标题】:Get current user with Spring @SubscribeMapping使用 Spring @SubscribeMapping 获取当前用户
【发布时间】:2017-12-20 00:00:19
【问题描述】:

我在一个严重依赖 WebSocket 进行数据交换的 Spring Boot 应用程序中使用 @SubscribeMapping。应用程序由 Sp​​ring Security 保护。

客户端我使用 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
    }
);

服务器端,如何在注解的方法中获取当前登录的用户?

@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

【问题讨论】:

    标签: java spring spring-boot websocket stomp


    【解决方案1】:

    您可以尝试添加Principal 对象作为方法参数。这个接口由Authentication 扩展,它有几个可用的实现(Spring 会根据你的配置注入好的实现)。

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

    This article 也可以帮到你。

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 2018-10-25
      • 2018-11-21
      • 2021-03-30
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多