我试图设置最简单的CORS支持,但完全没有效果。
我将这些教程作为帮助:
https://spring.io/guides/gs/rest-service-cors/
https://www.baeldung.com/spring-cors
springboot版本:2.1.4.RELEASE
我已经通过firefox,chrome和cli CURL提出了请求
我在四个CORS设置中玩过:
1。控制器级别对应于来源:
@CrossOrigin(origin = "some-non-existent-url")
@GetMapping(value = "/secret")
public String secretWelcome(){
return "Welcome at secret page!";
}
2。控制器级别的方法:
I know its silly, but I wanted to try that an endpoint accepts only GET but Crosorigin will allow only POST so GET request will fail.
@CrossOrigin(methods = RequestMethod.POST)
@GetMapping(value = "/secret")
public String secretWelcome(){
return "Welcome at secret page!";
}
3.Global Cors配置(不带控制器cors注释):
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("DELETE");
}
}
4。与第3点相同,但带有allowedOrigins(“ some-on-existent-url”)
我不知道这与我的spring安全配置有关,但这是:
a,一个用于所有时间身份验证的内容:
@Configuration
@Profile(value="prod")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
http.formLogin();
http.logout();
}
}
b,以及一个用于禁用端点保护的
@Configuration
@Profile(value="dev")
public class SecurityConfigurationDev extends WebSecurityConfigurerAdapter{
@Autowired
DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().permitAll();
}
}
我尝试了这些排列(之后所有带有DEV配置文件和PROD配置文件的4个cors配置)。
我的预期结果是能够禁用除一种方法之外的所有http方法,或者仅允许来自特定IP的请求。
结果:我能够执行来自任何IP的各种请求
这些之后,我来到了这个网站: https://medium.com/@baphemot/understanding-cors-18ad6b478e2b
我已经意识到我的spring服务器甚至没有在响应中发送Access-Controll *标头
我所得到的就是这个:
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 35
Date: Mon, 08 Apr 2019 11:00:14 GMT
所以也许我误解了CORS的全部用途,或者我的配置不好。