我正在实现一个这样的简单套接字:
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
从客户端:
function connect() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
和websocket配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
现在我想为套接字应用身份验证,以便不是所有客户端都可以连接到服务器。我可能看起来像
var socket = new SockJS('/gs-guide-websocket?token= a JWT token'); //or sth similar
来自客户端。
假设我可以隐藏检查前端代码的人的令牌,我如何从服务器端获取该令牌并验证它? (只要我有验证JWT的功能)
或者你有没有更好的方法来实现套接字连接的安全性?