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

Fer*_*nch 9 security ajax basic-authentication cors spring-boot

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

我在很多地方搜索过,包括这个答案,它指向官方文档中基于过滤器的 CORS 支持

到目前为止没有运气。

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

fetch('http://localhost:8080/api/lists', {
  headers: {
    'Authorization': 'Basic dXNlckB0ZXN0LmNvbToxMjM0NQ=='
  }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的网络安全配置:

@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

        http.httpBasic().and()
            .authorizeRequests()
            .antMatchers("/", "/index.html").permitAll()
            .anyRequest().fullyAuthenticated();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

在此处输入图片说明

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

在此处输入图片说明

ilo*_*una 9

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

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


小智 5

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

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

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

检查此链接以获取更多信息:https ://www.baeldung.com/spring-security-cors-preflight