默认情况下,第一个请求必须由您的浏览器生成,作为 CORS 的合同。由于存在预检标头,此请求由 Spring 的 CORS Processor 处理。
如果 Spring 通过发送适当的标头允许它,那么浏览器将生成您的实际请求,该请求将由您的休息控制器处理。
现在,如果您仍想自己处理预检请求,则必须扩展 CORSConfiguration 类并覆盖其方法。
注意: - 即使你这样做了,你的浏览器也会提出两个请求。
首先将由您的自定义覆盖方法解决,其次由您的控制器解决。
一般来说,不需要为 OPTIONS 定义控制器,因为您的应用程序中不需要 OPTIONS 请求。它如果需要[根据 CORS 合同]由浏览器自动引发,并且它将由 springs CORS 处理器处理。
配置 CORS(如果您没有使用 Spring-security 模块):
有3种方式
使用注解 @Crossorigin [per rest-api 或 per rest controller
基础]
使用全局 CORS 配置
扩展 CorsFilter
方式 1 (@CrossOrigin)
此注解可应用于类或方法。
示例:--
@RestController
@CrossOrigin(origins = {"http://localhost:8585"}, maxAge = 4800, allowCredentials = "false")
public class FetchOnPremData {
@RequestMapping(value = "/fetchData/{jiraid}", method = RequestMethod.OPTIONS)
public int options(@PathVariable String jiraid ,HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST");
response.setHeader("Allow", "HEAD,GET,PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Origin","*");
return 234;
}
}
或方法:
@RestController
public class FetchOnPremData {
@CrossOrigin
@RequestMapping(value = "/fetchData/{jiraid}", method = RequestMethod.GET)
public int options(@PathVariable String jiraid ,HttpServletResponse response) {
// your code
return 234;
}
方式 2:全局 Cors 配置
如果你想为你所有的 rest 控制器启用 cors 支持,那么使用这个选项。
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}
方式 3:使用 CorsFilter
如果你想要更好的控制,那么你可以更喜欢这个。
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
// This bean will override default cors filter
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
配置 CORS(如果您使用 Spring-Security 模块):
那么除了使用上述任何一种方式之外,您还必须将以下内容添加到您的配置中:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors().and()
...
}
}
参考:
Spring Security CORS Configuration documentation
Spring MVC CORS Configuration documentation