@Bean CorsConfigurationSource corsConfigurationSource() { return new CorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { var cors = new CorsConfiguration(); cors.setAllowedOrigins(List.of("*")); cors.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); cors.setAllowedHeaders(List.of("*")); return cors; } }; } @Override protected void configure(HttpSecurity http) throws Exception { // @formatter: off http .csrf() .disable() .cors() .configurationSource(corsConfigurationSource()) .and() .exceptionHandling()
Còn đây là config websocket
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/websocket") .setAllowedOriginPatterns("*").withSockJS(); }
Và khi em connect socket ở bên FE thì lỗi như này nè a 🙁
Access to XMLHttpRequest at 'http://localhost:8082/emaf/api/v1/websocket/info?t=1669656213092' from origin 'http://127.0.0.1:5500' 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.
Mong a hướng dẫn e cách fix bên BE ạ.
Nghĩa là em đang config cors ở 2 nơi nhỉ? 1 là ở filter, 2 là WebSocketConfig?
Dạ e đang config như vậy ạ,
Đoạn code này e có thể config setAllowedOrigins bằng domain của em và setAllowedHeaders khác *
và set thêm credentials = true nữa thì nó sẽ chạy được ạ. Nhưng vấn đề là lúc e build lên sever nginx thì FE lỗi CORS. Do khi config setAllowedOrigins thì nó ko thể set multiple origin và khi em add duy nhất 1 domain localhost 8080 thì nó vẫn báo multiple value. Nó duplicate localhost 8080 lên ạ
Nếu ở trong code em đã config cors thi nginx em không cần config nữa em ạ. Anh nghĩ là em nên config ở nginx thay vì config ở code java.
Còn lỗi ở trên câu hỏi, anh nghĩ là em chỉ cần disable cors là được em ạ.
Dạ vâng ạ. A có comment ở câu hỏi https://stackask.com/question/bug-sai-duong-dan-khi-config-ckeditor-len-live/#comment-1595 a vào xem giúp em vớ ạ
Ok em
Ở đây anh đang hiểu là em đang gộp chung http và websocket server vào làm 1 nhỉ?