我加入了自定義的基於令牌的認證爲我的春天的Web應用程序,並延長了彈簧的WebSocket相同如下圖所示春天的WebSocket發送給特定的人
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(new ChannelInterceptorAdapter() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
String jwtToken = accessor.getFirstNativeHeader("Auth-Token");
if (!StringUtils.isEmpty(jwtToken)) {
Authentication auth = tokenService.retrieveUserAuthToken(jwtToken);
SecurityContextHolder.getContext().setAuthentication(auth);
accessor.setUser(auth);
//for Auth-Token '12345token' the user name is 'user1' as auth.getName() returns 'user1'
}
}
return message;
}
});
}
}
客戶端代碼連接到插座
var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({'Auth-Token': '12345token'}, function (frame) {
stompClient.subscribe('/user/queue/greetings', function (greeting) {
alert(greeting.body);
});
});
從我的控制,我發送消息
messagingTemplate.convertAndSendToUser("user1", "/queue/greetings", "Hi User1");
當t他認證令牌12345token
用戶名是user1
。但是,當我發送消息到user1
,它沒有收到客戶端。有什麼我錯過了這個?
看到的是,我希望郵件只發送給特定的用戶。如果我使用@SendTo(「/ user/queue/greetings」),那麼應用程序將知道我想向哪個用戶發送消息。我也嘗試了你的建議,但沒有收到客戶端的任何通知。 – BiJ
我已經這樣做了。我會盡力找到我的代碼並將其發佈到此處。 –
這將是一個很大的幫助。 – BiJ