如何在Spring Boot中配置CORS和基本授权?

时间:2016-12-10 13:04:17

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

我正在尝试在已经设置了基本身份验证的Spring启动应用程序中配置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引导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;
    }
}

我的WebSecurityConfig:

@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。

enter image description here

在chrome dev工具的网络标签中,我看到了这个OPTIONS请求:

enter image description here

3 个答案:

答案 0 :(得分:3)

我认为您需要允许OPTION次请求进入您的网络安全配置。类似的东西:

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

答案 1 :(得分:2)

浏览器通过带有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

答案 2 :(得分: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");
      }
    };
  }

}