【问题标题】:Problem with CORS consuming Spring boot REST APICORS 使用 Spring Boot REST API 的问题
【发布时间】:2021-03-07 20:01:22
【问题描述】:

下午好

我有一个 React JS 应用程序。此应用使用 Spring Boot 和 Spring Security 消耗休息服务。

这是我的安全配置:

@Configuration
@EnableWebSecurity
public class ServiceSecurity extends WebSecurityConfigurerAdapter{
    
    @Override
    protected void configure(HttpSecurity http)
    {
        try 
        {
            http
            .csrf()
            .disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
            http.cors();            
           
        }         
        catch (Exception ex) 
        {
            Logger.getLogger(ServiceSecurity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    @Bean
    CorsConfigurationSource corsConfigurationSource() 
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://192.168.194.129:8080","http://192.168.193.8:8080","http://192.168.193.8:3000","http://192.168.193.6:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("cache-control","Content-Type","Access-Control-Allow-Origin","Access-Control-Allow-Headers","Access-Control-Allow-Credentials","Access-Control-Allow-Methods","Authorization","X-Requested-With","X-Frame-Options"));
        configuration.setExposedHeaders(Arrays.asList("Content-Type","Access-Control-Allow-Origin","Access-Control-Allow-Headers","Access-Control-Allow-Credentials","Access-Control-Allow-Methods","Authorization","X-Requested-With","X-Frame-Options"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration.applyPermitDefaultValues());        
        return source;
    }


}

如果我启用 chrome 扩展“允许 cors”,则只有当我从有效 URL(在 spring 安全配置 setAllowedOrigins 中)实现请求时,我才能获取所有数据。如果我尝试从另一个 URL 获取数据,chrome 控制台会显示 403 错误。

因此,我知道我的休息服务配置正在运行。

但是,如果关闭“允许 cors”chrome 扩展,我会收到以下错误: Access to fetch at 'http://192.168.193.8/WebService/obtenerFertilizantes' from origin 'http://192.168.193.8:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://192.168.193.8:3000, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Chrome 网络日志说: (失败)net::ERR_FAILED 获取

API 在 javascript 中通过 fetch 使用:

config = {
          method: 'GET',
          crossDomain:true,
          async: true,
          headers: {
              'Authorization': 'Basic ' + btoa(username + ":" + password),
              'Content-Type': 'application/json',                    
              'Accept': 'application/json',
              "Access-Control-Allow-Methods": "POST, GET",
              "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Origin, Authorization",
              "Access-Control-Allow-Credentials":true,
              "cache-control": "no-cache"
          }                
        };
        
        fetch("http://localhost/service/obtenerFertlizantes",config)
          .then(response => response.json())
          .then(responseJson => {
            setDatos(responseJson);
          });

感谢您的帮助。

【问题讨论】:

  • 不要将 Access-Control-* 标头放入您的开始请求中 - 并停止在 access-control-allow-origin 中发送多个值...错误清楚地告诉您您的服务器正在发送http://192.168.193.8:3000, *
  • 您也不需要在允许的标头/公开的标头中设置所有这些 access-Control-* 值...
  • 感谢您的推荐。但错误是一样的。新的标题是: headers: { 'Authorization': 'Basic' + btoa(username + ":" + password), 'Content-Type': 'application/json' }
  • 我不知道我要发送多个值的哪个部分。

标签: javascript java spring-boot cors fetch


【解决方案1】:

终于,我可以解决问题了。

API 休息服务在 Payara 服务器上。 该服务器在 default-web.xml 配置文件中配置了额外的 CORS。

我删除了有关 CORS 配置的行并且工作正常!

我只使用 spring 安全配置 CORS。

谢谢!

【讨论】:

    猜你喜欢
    • 2021-05-22
    • 2022-11-03
    • 2020-08-27
    • 1970-01-01
    • 2021-04-11
    • 2016-07-09
    • 2020-12-16
    • 2019-05-22
    相关资源
    最近更新 更多