【问题标题】:How to configure CORS and Basic Authorization in Spring Boot?如何在 Spring Boot 中配置 CORS 和基本授权?
【发布时间】:2017-04-25 20:14:03
【问题描述】:

我正在尝试在已设置基本身份验证的 Spring Boot 应用程序中配置 CORS。

我在很多地方搜索过,包括this answer,在官方文档中指向Filter based CORS support

到目前为止还没有运气。

我的 AJAX 请求就是这样完成的。如果从同一来源http://localhost:8080 完成,它可以工作。

fetch('http://localhost:8080/api/lists', {
  headers: {
    'Authorization': 'Basic dXNlckB0ZXN0LmNvbToxMjM0NQ=='
  }
}

AJAX 请求是从http://localhost:3000 的 React 应用程序完成的,所以我尝试了以下 Spring boot CORS 配置:

@Configuration
class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        // Maybe I can just say "*" for methods and headers
        // I just copied these lists from another Dropwizard project
        config.setAllowedMethods(Arrays.asList("GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD"));
        config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept",
            "Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods",
            "Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age",
            "Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Alternates",
            "Content-Range", "Content-Disposition", "Content-Description"));
        config.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

我的网络安全配置:

@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and()
            .authorizeRequests()
            .antMatchers("/", "/index.html").permitAll()
            .anyRequest().fullyAuthenticated();
    }
}

来自http://localhost:3000fetch 调用在控制台中显示此401 错误:

Fetch API 无法加载 http://localhost:8080/api/lists。回应 预检具有无效的 HTTP 状态代码 401。

在 chrome 开发工具的网络选项卡中,我看到了这个 OPTIONS 请求:

【问题讨论】:

    标签: ajax security spring-boot cors basic-authentication


    【解决方案1】:

    试试这个:

    @Configuration
    public class CorsConfig {
    
      @Bean
      public CorsFilter corsFilter() {
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(false); //updated to false
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
      }
    
      @Bean
      public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
          @Override
          public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/").allowedOrigins("http://localhost:3000");
          }
        };
      }
    
    }
    

    【讨论】:

    • 谢谢,但结果相同...我还将配置设置添加到您的解决方案中,但没有任何变化。我没有使用 Spring MVC,但我也包含了您的 WebMvcConfigurer 以防万一。
    • 你在使用 Boot 和 Angular 2
    • 你为什么要问?我现在正在使用 React 来尝试它,但我也打算尝试 Angular 2。无论如何,我正在使用fetch 函数调用@RestController。我的意思是调用中不涉及任何 React 组件。
    【解决方案2】:

    我认为您需要允许 OPTION 请求进入您的网络安全配置。比如:

    .antMatchers(HttpMethod.OPTIONS, "/your-url").permitAll()

    【讨论】:

    • 谢谢!你是对的!现在,为了看看它是否有效,我使用了.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()。它适用于我的FilterRegistrationBean。也许它也适用于CorsFilter,但问题是 OPTIONS 调用被阻止了。
    【解决方案3】:

    浏览器通过带有 OPTIONS 标头的请求检查 CORS 设置。如果您配置了授权,OPTIONS 请求将被视为未经授权而被阻止。

    您可以通过 WebConfigurerAdapter 中的 cors 支持简单地允许 OPTIONS 请求。

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // ...
            http.cors();
        }
    }
    

    查看此链接了解更多信息:https://www.baeldung.com/spring-security-cors-preflight

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 2019-09-29
      • 2021-06-14
      • 1970-01-01
      • 2021-08-02
      • 2019-05-05
      • 2014-09-15
      • 2016-08-26
      相关资源
      最近更新 更多