【发布时间】:2021-10-14 18:36:53
【问题描述】:
我有一个服务器应用程序:
@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>
【问题讨论】:
标签: java spring-boot cors