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

问题描述 投票:1回答:1

我正在研究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.
java websocket spring-websocket stomp sockjs
1个回答
0
投票
@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配置。希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.