我有应用程序 StompJs 从下面的服务器订阅消息:
客户:
this.stompClient = this.createStormClient();
this.stompClient.connect(this.socket.header, frame => {
console.log(frame);
if (this.stompClient) {
this.stompClient.subscribe(`topic/hello`,(data:any) => {
console.log('subscribe hello finish.')
console.log(data);
});
}
});
createStormClient():any {
let ws = new SockJS('http://127.0.0.1:8084/api/websocket');
let stompClient = Stomp.over(ws);
return stompClient;
}
服务器:
@Configuration
public class WebSocketAuthorizationSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(final MessageSecurityMetadataSourceRegistry messages) {
// You can customize your authorization mapping here.
messages
.simpSubscribeDestMatchers("topic/hello").authenticated()
.anyMessage().authenticated();
}
// TODO: For test purpose (and simplicity) i disabled CSRF, but you should re-enable this and provide a CRSF endpoint.
@Override
protected boolean sameOriginDisabled() {
return true;
}
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer, ChannelInterceptor {
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtUserDetailsService userSerive;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic","/queue");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/api/websocket").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptor() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
List<String> authorization = accessor.getNativeHeader("X-Authorization");
String accessToken = authorization.get(0);
if (accessToken != null && accessToken.startsWith("Bearer ")) {
String jwtToken = accessToken.substring(7);
String userUrl = jwtTokenUtil.getUsernameFromToken(jwtToken);
if (!StringUtil.isEmpty(userUrl)) {
UserDetails userDetails = userSerive.loadUserByUsername(userUrl);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, "", userDetails.getAuthorities());
accessor.setUser(authentication);
}
}
}
return message;
}
});
}
}
控制器发送消息
public class Controller {
@Autowired
private SimpMessagingTemplate template;
@RequestMapping(value = "/api/hello", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> newBook(@RequestBody Long id) {
try {
template.convertAndSend("topic/hello", "hello broker message");
return new ResponseEntity<Boolean>(true,HttpStatus.OK);
} catch(Exception ex) {
log.error("new quick book error" + ex.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
}
}
控制台显示框架:
[日志] 帧 {command: "CONNECTED", headers: {user-name: "7", heart-beat: "0,0", version: "1.1"}, body: "", toString: function} (tabs -home-home-module.js,第 293 行)
并订阅:
>>> SUBSCRIBE
id:sub-0
destination:topic/hello
网络
a["CONNECTED\n版本:1.1\nheart-beat:0,0\nuser-name:7\n\n\u0000"]
["SUBSCRIBE\nid:sub-0\ndestination:topic/hello\n\n\ u0000"]
控制台在订阅中没有我的预期
console.log('subscribe hello finish.')
console.log(data);