首页 > 解决方案 > 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>

标签: javaspring-bootcors

解决方案


请注意,CORS 仅适用于从浏览器发出的请求。当您使用其他服务查询您的服务RestTemplate时,您无需担心 CORS 或任何相关限制。

还请查看CORS - 它是客户端的东西、服务器端的东西还是传输级别的东西?它提供了有关 CORS 工作原理的更多详细信息。


推荐阅读