使用 sockjs 和 stomp 进行 /info 请求期间没有 cookie

2024-05-13

我正在尝试将 Spring Security 与 websockets 一起使用。作为一个例子,我正在使用 spring-websocket-chat (https://github.com/salmar/spring-websocket-chat https://github.com/salmar/spring-websocket-chat) — 来自演讲“深入研究 websockets”的演示应用程序。在该应用程序中,CookieHttpSessionStrategy 用于存储会话 ID,在身份验证期间存储的 Cookie 与 /info 请求一起发送。下面是演示通过 sockjs 连接到服务器的代码(此请求发送 cookie)https://github.com/salmar/spring-websocket-chat/blob/master/src/main/webapp/js/services.js https://github.com/salmar/spring-websocket-chat/blob/master/src/main/webapp/js/services.js。我编写了自己的客户端,使用 sockjs 和 stomp,但在 /info 请求期间没有发送 cookie。这是我的代码

$connectButton.click(function () {
    var serverHost = $host.val();
    console.log("sockjs created");
    stomp = Stomp.over(new SockJS(serverHost));
    console.log("stomp over");
    stomp.connect({},
        function () {
            console.log("connected");
        },
        function () {
            console.log("error");
        })
    console.log("pressed");
});

据我所知,你不能将cookie传递给SockJS(尤其是同源策略)。然而,使用最新的 SockJS 1.0.3,您可以将查询参数作为连接 URL 的一部分传递。因此,您可以发送一些 JWT 令牌来授权会话。

  var socket = new SockJS('http://localhost/ws?token=AAA');
  var stompClient = Stomp.over(socket);
  stompClient.connect({}, function(frame) {
      stompClient.subscribe('/topic/echo', function(data) {
        // topic handler
      });
    }
  }, function(err) {
    // connection error
  });

现在所有与w​​ebsocket相关的请求都会有参数“?token=AAA”

http://localhost/ws/515/z45wjz24/websocket?token=AAA http://localhost/ws/515/z45wjz24/websocket?token=AAA

然后使用 Spring,您可以设置一些过滤器,它将使用提供的令牌来识别会话。

当 UI 和服务器同源时,PS cookie 会自动获取。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 sockjs 和 stomp 进行 /info 请求期间没有 cookie 的相关文章

随机推荐