spring - 我的 Spring Boot 项目中有一个 CORS 实现我想知道这是正确的方法吗?
问题描述
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity https) throws Exception {
https.headers().disable();
https.csrf().disable();
https.headers().cacheControl();
https.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(final HttpServletRequest request) {
return new CorsConfiguration().applyPermitDefaultValues();
}
});
}
}
我尝试了上述配置并且工作正常而且我也相信在 Spring 中我们在控制器级别有 @CrossOrigin 注释:所以在实现方面这是最可取的
解决方案
我认为方法很好。基于注释的问题是它们在编译时本质上是静态的 - 但这可能在您的用例中完美运行。
与 Spring 中的许多事情一样,有不止一种有效的做事方式,哪种“最好”取决于您的情况和要求。如果您有一个静态定义良好的 CORS 策略,那么基于注释的可能是最简单且对您的代码库的干扰最小的。
如果您需要更动态或更灵活的东西 - 可能基于运行时的属性设置。在我最新的项目中,我处理 CORS 的方式是这样的:
@Configuration
@EnableWebSecurity
@Slf4j
@EnableConfigurationProperties({CORSProperties.class})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CORSProperties properties;
@Override
protected void configure(final HttpSecurity http) throws Exception {
log.info("Configuring web security....");
http.headers()
.and()
.cors();
}
@Bean
public UrlBasedCorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(properties.getAllowedOrigins());
configuration.setAllowedMethods(allHttpMethods());
configuration.setAllowedHeaders(asList(CrossDomainCsrfTokenRepository.XSRF_HEADER_NAME, CONTENT_TYPE));
configuration.setExposedHeaders(asList(LOCATION, CrossDomainCsrfTokenRepository.XSRF_HEADER_NAME));
configuration.setAllowCredentials(true);
configuration.setMaxAge(HOURS.toSeconds(properties.getMaxAgeInHours()));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
private List<String> allHttpMethods() {
return Stream.of(HttpMethod.values())
.map(HttpMethod::name)
.collect(toList());
}
}
这并不是说这一定是最好的方法,但它对我有用并且足够灵活。
我建议您还检查一下 Spring Boot 示例:https ://spring.io/guides/gs/rest-service-cors/ ,它显示了使用 Web 配置器适配器的另一种模式:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}
推荐阅读
- sql-server - SQL Server T-SQL:对两个表中的数据进行分组时遇到问题
- python - Python - Pandas 使用字符串和浮点数重新采样数据帧
- excel - 使用 VBA 将 Excel 文件上传到 SharePoint
- javascript - tiptap - 在当前节点下方 / 末尾插入节点
- .net-core - 为 .NET Core 3.1/IdentityModel 5.1 使用 ResourceOwnerPassword 流
- asp.net-mvc - 在 ASP.net core mvc 上运行 unity webgl 文件
- django - Django Rest Framework 不会正确序列化 GeoJSON
- sql - Oracle SQL:无法创建过程
- php - 在 Ununtu 中激活 PHP 扩展
- gis - Netlogo 变量作为面板格式的 txt (csv) 文件并与 GIS 文件链接