gpt4 book ai didi

java - 连接 WebSocket 时出现 'Access-Control-Allow-Origin' 错误如何修复?

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:05 24 4
gpt4 key购买 nike

我正在开发一个 SockJS 和 WebSocket 类型的项目,在前端我使用 React,在后端使用 spring 的 WebSockets 实现。但当我尝试连接到 WebSocket 时,出现 CORS 错误。

Access to XMLHttpRequest at 'http://localhost:8080/ws/info?t=1579096675068' 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.

在 Java 项目中,我包含了此 CORS 配置:

@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration configuration = new CorsConfiguration();
configuration.applyPermitDefaultValues();
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.addAllowedOrigin("*");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
source.registerCorsConfiguration("/**", configuration);
return source;
}

至于 WebSecurity 类上的 configure 方法,我已包含此内容:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}

我像这样添加我的套接字端点:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}

在前端,我使用 connect 方法连接到我的 WebSocket:

connect = () => {
const Stomp = require("stompjs");
let SockJS = require("sockjs-client");
SockJS = new SockJS("http://localhost:8080/ws");
stompClient = Stomp.over(SockJS);
stompClient.connect({}, this.onConnected, this.onError);
};

我尝试将 registerStompEndpoints 方法上的 URL 显式设置为 http://localhost:3000,但没有效果。还在前端的 package.json 上添加了一个代理到 http://localhost:8080/,但它仍然给出相同的错误。我需要在我的 corsConfigurationSource 上做些什么才能使其正常工作吗?

更新

当我执行以下 configure 方法时,它解决了 WebSocket 问题,因为它可以连接到它,但我失去了访问应用程序其他路由的能力,因为它给出了另一个错误。

protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/ws").permitAll()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable();
}

另一个错误:

Access to XMLHttpRequest at 'http://localhost:8080/auth/me' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

最佳答案

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.authorizeRequests()
.antMatchers("/ws/**").permitAll()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {

final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.addAllowedOrigin("*");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
configuration.applyPermitDefaultValues();
source.registerCorsConfiguration("/api/**", configuration);
source.registerCorsConfiguration("/auth/*", configuration);
source.registerCorsConfiguration("/login", configuration);
return source;
}

我最终使用它作为我的网络安全。总而言之,我在 configure 方法中添加了 .antMatchers("/ws/**").permitAll() 。因此,我允许所有发送到我的 WebSocket 端点的请求,并在除 corsConfigurationSource 方法上的 /ws 路由之外的所有其他路由上显式注册 CORS 配置。希望这会有所帮助。

关于java - 连接 WebSocket 时出现 'Access-Control-Allow-Origin' 错误如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59753263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com