java - Spring Boot 应用程序允许跨源请求,但它不应该
问题描述
我有一个服务器应用程序:
@RestController
@SpringBootApplication
public class ServerApplication {
@GetMapping("/data")
public ResponseEntity<String> getData() {
return ResponseEntity.ok("Some Data.");
}
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
和客户端应用程序:
@RestController
@SpringBootApplication
public class ClientApplication {
RestTemplate restTemplate = new RestTemplate();
@GetMapping("/test")
public ResponseEntity<String> test(){
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8023/data", String.class);
return ResponseEntity.ok("Received: " + response.getBody());
}
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
两者都具有完全相同的安全配置(启用 Spring 安全性):
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll();
}
}
我预计这个 restTemplate 调用会失败,因为我没有使用 @CrossOrigin 或任何其他方法激活 CORS。但这工作得很好。当我搜索类似的问题时,我只找到关于为什么不能到达终点的问题,而不是关于为什么可以到达的问题。
两个应用程序共享相同的依赖项:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
解决方案
请注意,CORS 仅适用于从浏览器发出的请求。当您使用其他服务查询您的服务RestTemplate
时,您无需担心 CORS 或任何相关限制。
还请查看CORS - 它是客户端的东西、服务器端的东西还是传输级别的东西?它提供了有关 CORS 工作原理的更多详细信息。
推荐阅读
- c++ - “const char *”类型的默认参数与“char *”类型的参数不兼容
- sql - 为什么 Access 需要我的查询参数?
- java - 有没有办法通过代码从远程开始 JFR 监控/记录?
- java - 在生产中编译时错误构建 jhipster
- amazon-web-services - 为什么ansible脚本-启动配置-开发错误?
- java - 如何在 G1GC 中触发老年代的收集
- regex - 正则表达式用于匹配字符串后的字符串到逗号
- python - 尽管其他数据库连接正常,但从 Python 连接时出现“数据库不存在”错误
- python - 使用字典查找和替换 CSV 文件中特定列中的值
- ios - 应用程序在后台时未调用 didReceive 和 willPresent