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

bfrts1fy  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(174)

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

  1. @Configuration
  2. @EnableWebSocketMessageBroker
  3. public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
  4. @Override
  5. public void registerStompEndpoints(StompEndpointRegistry registry) {
  6. registry.addEndpoint("/socket")
  7. .setAllowedOriginPatterns("*")
  8. .withSockJS();
  9. }
  10. @Override
  11. public void configureMessageBroker(MessageBrokerRegistry registry) {
  12. registry.setApplicationDestinationPrefixes("/app")
  13. .enableSimpleBroker("/message");
  14. }
  15. }

字符串
这是我的控制器:

  1. @Controller
  2. public class WebSocketController {
  3. private final SimpMessagingTemplate template;
  4. @Autowired
  5. WebSocketController(SimpMessagingTemplate template){
  6. this.template = template;
  7. }
  8. @MessageMapping("/send/message")
  9. public void sendMessage(String message){
  10. System.out.println(message);
  11. this.template.convertAndSend("/message", message);
  12. }
  13. }


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

  1. import { Injectable } from '@angular/core';
  2. declare var SockJS: any;
  3. declare var Stomp: any;
  4. @Injectable({
  5. providedIn: 'root',
  6. })
  7. export class WebSocketService {
  8. constructor() {
  9. this.initializeWebSocketConnection();
  10. }
  11. stompClient: any;
  12. msg: string[] = [];
  13. initializeWebSocketConnection() {
  14. const serverUrl = 'http://localhost:8080/socket';
  15. const ws = new SockJS(serverUrl);
  16. this.stompClient = Stomp.over(ws);
  17. const that = this;
  18. this.stompClient.connect({}, function(frame: any) {
  19. that.stompClient.subscribe('/message', (message: any) => {
  20. if (message) {
  21. that.msg.push(message);
  22. }
  23. });
  24. });
  25. }
  26. sendMessage(message: string) {
  27. this.stompClient.send('/app/send/message' , {}, message);
  28. }
  29. }


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

ugmeyewa

ugmeyewa1#

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

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

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

相关问题