Spring Boot Application允许跨域请求



我有一个服务器应用:

@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工作原理的详细信息。

正如这篇文章所说,Spring RestTemplate调用API工作,但jQuery失败了,因为同源策略

在web浏览器上应用同源策略。https://en.wikipedia.org/wiki/Same-origin_policy.

@CrossOrigin注释只是将所需的标头添加到响应中,这样浏览器就不会抛出CORS异常。

我不能评论,但是不,您的应用程序服务器,不阻止来自其他来源的调用(默认情况下)

最新更新