spring-boot - 由 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 --
解决方案
我找到了解决我的问题的方法。自定义标头必须在 CorsConfigurationSource bean 中公开。添加这行代码,允许跨域请求获取自定义标头“链接”作为响应。
configuration.addExposedHeader("Link");
推荐阅读
- html - 弹性列容器中项目之间的间距
- javascript - Puppeteer:for 循环 - 语法问题
- html - 背景图像 (CSS) 不会出现在网站上
- python-3.x - Selenium Wire Chrome 驱动程序失去互联网连接
- c# - 在 MVC 中将 ID 替换为名称
- flutter - Flutter TextField:多行,但不换行
- angular - lodash debounce cancel() 不停止 debounce 执行
- python - 我可以使用什么 Python 或 CLI 调用来终止 AWS Spot 实例并从 Spot 实例本身发出请求?
- c# - 主线程处理后如何再次获取 DBContext?
- java - 使用 Intellij 和 Java ME 的语言级别“1.4”不支持泛型