【发布时间】: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
【问题讨论】:
-
我添加了 -- EDIT 1 -- 当客户端在同一个端口(同源)和不同端口时,带有响应头的屏幕截图。
-
查看 Spring Security 的
DefaultCorsProcessor的调试日志。如果是 CORS 问题,您应该在那里阅读。 -
两个请求都得到 200 吗?还是你得到了 401?
-
两个请求的状态都是 200。
标签: spring-boot spring-security cors