注解在controller或者方法上,不写任何参数默认允许所有 origins。
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)@RestController@RequestMapping("/account")public class AccountController { @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") public void remove(@PathVariable Long id) { // ... }}
或者
@CrossOrigin(maxAge = 3600)@RestController@RequestMapping("/account")public class AccountController { @CrossOrigin("http://domain2.com") @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") public void remove(@PathVariable Long id) { // ... }}
全局配置
@Configurationpublic class WebConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/success") .allowedOrigins("http://com.myhost:8080")// .allowedMethods("PUT", "DELETE")// .allowedHeaders("header1", "header2", "header3")// .exposedHeaders("header1", "header2") .allowCredentials(false).maxAge(3600); } }; }}
关于 SpringSecurity 支持 cors
除了需要配置全局CORS以外,再添加一个 cors().and()即可。
protected void configure(HttpSecurity http) throws Exception { http .headers() .frameOptions() .sameOrigin() .and() // disable CSRF, http basic, form login// .csrf().disable() // 跨域支持 .cors().and() .authorizeRequests() .antMatchers("/user/**").authenticated() .anyRequest().permitAll() ....