如何修复 Spring Boot WebSocket 应用程序中的“Access-Control-Allow-Origin”问题?

may*_*ack 5 cors reactjs spring-boot spring-websocket

全部。我是 Spring Boot 和 Websocket 的新手。这是我的第一个集成 React 和 Spring Boot 项目,我目前正在使用 WebSocket 构建一个带有后端的聊天应用程序。

如前所述,我的前端是在 React (localhost:3000) 中构建的,但是当尝试调用后端/聊天应用程序时,我收到错误:

Access to XMLHttpRequest at 'http://localhost:9090/ws/info?t=1652731448126' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Run Code Online (Sandbox Code Playgroud)

我尝试查找一些可能的解决方案,例如使用@CrossOrigin(origins = "https://localhost:3000")and@CrossOrigin(origins = "http://localhost:3000")但这并没有改变任何东西。我也尝试过(@CrossOrigin(origins = "*")但没有运气。这两项努力都导致了相同的错误消息。

聊天控制器:

package com.project2.chatapi.controller;

import com.project2.chatapi.models.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;

@CrossOrigin(origins = "https://localhost:3000")
@Controller
public class ChatController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * Handles messages coming into the public chatroom
     * @param message
     * @return message
     */
    @MessageMapping("/message")  // /app/message
    @SendTo("/chatroom/public")
    public Message receivePublicMessage(@Payload Message message) {
        return message;
    }

    /**
     * Handles messages being sent to a private chat
     * Receives the message from a user and sends to another user
     * @param message
     * @return message
     */
    @MessageMapping("/private-message")
    public Message receivePrivateMessage(@Payload Message message) {
        simpMessagingTemplate.convertAndSendToUser(message.getReceiverName(), "/private", message); // listens to /user/name/private
        return message;
    }
}
Run Code Online (Sandbox Code Playgroud)

WebsocketConfig 类:

package com.project2.chatapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * Adding endpoint to the chat
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("http://localhost:3000")
                .withSockJS();
    }

    /**
     * Configuring application destination prefixes
     * Adding topic prefixes - chatroom, and user
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/chat");
        registry.enableSimpleBroker("/chatroom","/user");
        registry.setUserDestinationPrefix("/user");
    }

    @Bean
    public WebMvcConfigurer corsConfig() {
        return new WebMvcConfigurer() {

            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowedOrigins("http://localhost:3000");
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

调用后端的React方法:

    const connect = (e) => {
        e.preventDefault();
        setUserData({...userData, "username": username});
        let Sock = new SockJS('http://localhost:9090/ws');
        stompClient = over(Sock);
        stompClient.connect({},onConnected, onError);
    }
Run Code Online (Sandbox Code Playgroud)

我还尝试实施有关 setAllowedOrigins 的不同可能的解决方案。我尝试了一些组合,包括(“http://localhost:3000”)和(“*”)——但同样,它似乎并没有改变我的错误消息。

我已经坚持这个问题好几天了。任何帮助将不胜感激。谢谢你!

更新:这些是自最初发布此问题以来我尝试过的其他操作。不幸的是,我在这些尝试中仍然遇到同样的错误。

  1. 我尝试添加过滤器
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    final Logger logger = LoggerFactory.getLogger(SimpleCORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        logger.info("Initializing Middleware");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest requestToUse = (HttpServletRequest)servletRequest;
        HttpServletResponse responseToUse = (HttpServletResponse)servletResponse;

        responseToUse.setHeader("Access-Control-Allow-Origin",requestToUse.getHeader("Origin"));
        filterChain.doFilter(requestToUse,responseToUse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 我尝试在我的配置文件中添加 cors 映射
  2. 还尝试将 CorsConfigurationSource 添加到我的配置文件中
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {

    // can possibly delete
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowCredentials(false)
                .maxAge(3600)
                .allowedHeaders("Accept", "Content-Type", "Origin",
                        "Authorization", "X-Auth-Token")
                .exposedHeaders("X-Auth-Token", "Authorization")
                .allowedMethods("POST", "GET", "DELETE", "PUT", "OPTIONS");
    }

    /**
     * Adding endpoint to the chat
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws/*")
                .setAllowedOrigins("http://localhost:3000")
                .withSockJS();
    }

    /**
     * Configuring application destination prefixes
     * Adding topic prefixes - chatroom, and user
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/chat");
        registry.enableSimpleBroker("/chatroom","/user");
        registry.setUserDestinationPrefix("/user");
    }
//
    @Bean
    public WebMvcConfigurer corsConfig() {
        return new WebMvcConfigurer() {

            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/ws/**")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowedOrigins("http://localhost:3000");
            }
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setExposedHeaders(Arrays.asList("Authorization"));
        configuration.addAllowedOrigin("http://localhost:3000");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.applyPermitDefaultValues();
        return source;
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 将 cors 映射和 WebMvcConfigurer 添加到我的主应用程序
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*").allowedOrigins("http://localhost:3000");
            }
        };
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 我检查了我的 google chrome 浏览器中的网络日志,Access-Control-Allow-Origin: *尽管进行了所有配置,它仍然显示。

小智 2

这解决了我的问题

 @Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry
    .setAllowedOrigins("http://localhost:3000") // not setAllowedOriginPatterns  
    .withSockJS();
}
Run Code Online (Sandbox Code Playgroud)