我正在开发一个基于 Spring 4 WebSocket 的多人游戏。
我的服务器是无状态的,因此为了识别玩家,我使用令牌。
经过一段时间的努力,如何通过 WebSockets 识别玩家,我想出了这个解决方案:在客户端玩家寄存器上,如下所示:
var sockjs = new SockJS("http://mygame/games/", null, {server : token});
这会将令牌添加到网址中,我已经使用 spring security 设置了一个过滤器:
String requestURI = request.getRequestURI();
String[] parts = StringUtils.split(requestURI, "/");
if (parts.length == 4) {
String token = parts[1];
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(Role.ROLE_MULTIPLAYER)));
SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken(token, "MULTIPLAYER", authorities));
}
它有效!在所有 WebSockets 请求中,我都有一个主体集。
然而有些浏览器似乎不支持这一点,在Safari例如,未设置主体,在调试请求时,我看到 URL 是正确的并且过滤器有效,但未设置主体。 IE、Chrome 和 FF 也是如此。
我正在使用 STOMP(https://github.com/jmesnil/stomp-websocket https://github.com/jmesnil/stomp-websocket)作为消息协议。
为什么浏览器之间有不同的行为?
是 Spring 还是 Client 的问题?