You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot Data Rest中强制启用CORS限制?

如何在Spring Data REST中拒绝跨域请求?

有两种可靠的实现方式:

1. 直接关闭Spring Data REST的默认CORS支持

在配置文件中添加参数,彻底禁用Spring Data REST自带的CORS配置:

# application.properties
spring.data.rest.cors.enabled=false

或者使用YAML格式:

# application.yml
spring:
  data:
    rest:
      cors:
        enabled: false

关闭后,Spring Data REST的端点会和普通MVC端点保持一致,默认拒绝所有跨域请求。

2. 自定义严格的CORS规则(按需限制)

如果需要更精细的控制(比如仅允许特定域名,或完全拒绝跨域),可以实现RepositoryRestConfigurer接口,重写configureCors方法来覆盖默认规则:

import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

@Configuration
public class RestCorsConfig implements RepositoryRestConfigurer {

    @Override
    public void configureCors(CorsRegistry corsRegistry, RepositoryRestConfiguration config) {
        // 清空默认映射,设置拒绝所有跨域请求
        corsRegistry.addMapping("/api/**").allowedOrigins();
        // 若需仅允许特定域名,可改为:
        // corsRegistry.addMapping("/api/**").allowedOrigins("http://your-allowed-domain.com");
    }
}

补充说明

你自定义的/api2端点CORS限制正常生效,是因为这类手动编写的Spring MVC端点默认没有启用CORS支持,必须显式配置才允许跨域,这和Spring Data REST的默认宽松配置形成了鲜明对比。

内容的提问来源于stack exchange,提问作者Franco G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:37:08