我在我的Spring Boot项目中有一个CORS实现,我想知道这是正确的方法吗?
我尝试了上述配置,效果很好我在我的Spring Boot项目中有一个CORS实现,我想知道这是正确的方法吗?,spring,spring-boot,spring-security,cors,Spring,Spring Boot,Spring Security,Cors,我尝试了上述配置,效果很好 我还相信,在Spring中,我们在控制器级别有@CrossOrigin注释:因此,在实现方面,哪一种注释更可取?我认为这种方法很好。基于注释的注释在编译时本质上是静态的,但这在您的用例中可能非常有效 和春天的许多事情一样,有不止一种有效的方式来做事情,哪种方式最好取决于您的情况和需求。如果您有一个静态的定义良好的CORS策略,那么基于注释的策略可能是对代码库最简单、干扰最小的策略 如果您需要更具动态性或灵活性的内容—可能基于运行时的属性设置。在我最近的项目中,我处理C
我还相信,在Spring中,我们在控制器级别有@CrossOrigin注释:因此,在实现方面,哪一种注释更可取?我认为这种方法很好。基于注释的注释在编译时本质上是静态的,但这在您的用例中可能非常有效 和春天的许多事情一样,有不止一种有效的方式来做事情,哪种方式最好取决于您的情况和需求。如果您有一个静态的定义良好的CORS策略,那么基于注释的策略可能是对代码库最简单、干扰最小的策略 如果您需要更具动态性或灵活性的内容—可能基于运行时的属性设置。在我最近的项目中,我处理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();
}
});
}
}
@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());
}
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}