如何使用Spring Security在Sping Boot 和Angular之间连接Web套接字?

bfrts1fy  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(54)

我正在使用Sping Boot 和Angular中的Web套接字进行一个真实的实时聊天项目。我在我的API中使用Spring Security。
下面是我在API中的WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/socket")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app")
                .enableSimpleBroker("/message");
    }
}

字符串
这是我的控制器:

@Controller
public class WebSocketController {

    private final SimpMessagingTemplate template;

    @Autowired
    WebSocketController(SimpMessagingTemplate template){
        this.template = template;
    }

    @MessageMapping("/send/message")
    public void sendMessage(String message){
        System.out.println(message);
        this.template.convertAndSend("/message",  message);
    }
}


当我用Postman在'http://localhost:8080/socket'上发送请求时,
现在,这是我的Angular服务来设置连接:

import { Injectable } from '@angular/core';
declare var SockJS: any;
declare var Stomp: any;

@Injectable({
  providedIn: 'root',
})
export class WebSocketService {
  
  constructor() {
    this.initializeWebSocketConnection();
  }
  stompClient: any;
  msg: string[] = [];
  initializeWebSocketConnection() {
    const serverUrl = 'http://localhost:8080/socket';
    const ws = new SockJS(serverUrl);
    this.stompClient = Stomp.over(ws);
    const that = this;
    this.stompClient.connect({}, function(frame: any) {
      that.stompClient.subscribe('/message', (message: any) => {
        if (message) {
          that.msg.push(message);
        }
      });
    });
  }
  
  sendMessage(message: string) {
    this.stompClient.send('/app/send/message' , {}, message);
  }
}


SockJs.min.js和stomp.min.js都在我的index.html文件中声明。
当我从我的客户端angular测试这个连接时,我得到以下错误:x1c 0d1x
我在API控制台没有任何错误,我不知道为什么我得到这个禁止错误。
有人知道为什么吗?非常感谢!

ugmeyewa

ugmeyewa1#

setAllowedOrigins("*")可能无法按预期的方式进行身份验证。
您可能需要显式添加您的来源。(例如["http://localhost:4200"]
此外,您还可以通过调试拦截器来获得更多信息。

org.springframework.security.messaging.web.socket: DEBUG
org.springframework.web.socket.server: DEBUG

字符串
无法将消息发送到ExecutorSubscribableChannel[clientInboundChannel]的潜在重复

相关问题