首页 > 解决方案 > 由 CORS 阻止的 Spring Boot 自定义响应标头

问题描述

我有 Spring Boot 应用程序,它为对象列表提供 GET REST API 端点。该列表具有默认分页,并提供自定义“链接”HTTP 标头,其中包含基于导航中当前页面的下一页和上一页的信息,供客户端使用。

链接 HTTP 标头示例

link: <http://localhost:8080/api/v1/articles?page=1&size=1>; rel="next", <http://localhost:8080/api/v1/articles?page=4&size=1>; rel="last"' 

当客户端和 Web 服务器使用相同的来源时,则包含标头。但是,当客户端具有不同的来源时,我无法在响应标头中包含链接标头。该应用程序具有 CORS 配置,但我找不到任何使其包含我的自定义标头的内容。仅包含默认响应标头。

知道如何在 CORS 响应中包含自定义 HTTP 标头吗?

 @Configuration
 @EnableWebSecurity
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public SpringDataUserDetailsService customUserDetailsService() {
        return new SpringDataUserDetailsService();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();

        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/admin").authenticated().and().formLogin();
    }
 }

-- 编辑 1 --

客户端与 Web 服务器同源时的响应标头

客户端在另一个端口上时的响应标头

标签: spring-bootspring-securitycors

解决方案


我找到了解决我的问题的方法。自定义标头必须在 CorsConfigurationSource bean 中公开。添加这行代码,允许跨域请求获取自定义标头“链接”作为响应。

configuration.addExposedHeader("Link");

推荐阅读