【问题标题】:Spring boot custom response header blocked by CORS由 CORS 阻止的 Spring Boot 自定义响应标头
【发布时间】:2020-09-10 04:24:52
【问题描述】:

我有提供 GET REST API 端点到对象列表的 Spring Boot 应用程序。该列表具有默认分页,并提供自定义“链接”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--

Response headers when the client is of the same origin as web server

Response headers when the client is on the other port

【问题讨论】:

  • 我添加了 -- EDIT 1 -- 当客户端在同一个端口(同源)和不同端口时,带有响应头的屏幕截图。
  • 查看 Spring Security 的DefaultCorsProcessor 的调试日志。如果是 CORS 问题,您应该在那里阅读。
  • 两个请求都得到 200 吗?还是你得到了 401?
  • 两个请求的状态都是 200。

标签: spring-boot spring-security cors


【解决方案1】:

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

configuration.addExposedHeader("Link");

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 2021-06-20
    • 2019-12-15
    • 2017-12-16
    • 2018-06-03
    • 2014-10-10
    • 2021-06-29
    • 2020-04-20
    • 1970-01-01
    相关资源
    最近更新 更多