连接到WebSocket时如何解决“ Access-Control-Allow-Origin”错误?

我正在研究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;
}

对于configure类上的WebSecurity方法,我包括了:

@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问题,因为它可以连接到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.
vcdok000 回答:连接到WebSocket时如何解决“ Access-Control-Allow-Origin”错误?

@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;
}

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

本文链接:https://www.f2er.com/2764644.html

大家都在问