跳到主要内容
版本:5.1.1

配置 CORS

Doubao 中英对照 Configuring CORS

出于安全原因,浏览器会禁止对当前源之外的资源发起 AJAX 调用。在处理由浏览器发出的客户端 HTTP 请求时,您会希望允许访问特定的 HTTP 资源。

自 2.6 起,Spring Data REST 支持跨域资源共享(CORS),这是通过 Spring 的 CORS 支持实现的。

仓库接口 CORS 配置​

您可以在仓库接口上添加 @CrossOrigin 注解,从而为整个仓库启用 CORS。默认情况下,@CrossOrigin 允许所有源和 HTTP 方法。以下示例展示了一个跨域仓库接口的定义:

@CrossOrigin
interface PersonRepository extends CrudRepository<Person, Long> {}

在前述示例中,整个 PersonRepository 都启用了 CORS 支持。@CrossOrigin 提供了若干属性来配置 CORS 支持,如下例所示:

@CrossOrigin(origins = "http://domain2.example",
methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE },
maxAge = 3600)
interface PersonRepository extends CrudRepository<Person, Long> {}

前述示例通过提供一个源并将其限制为 GET、POST 和 DELETE 方法、最大存活时间为 3600 秒,从而为整个 PersonRepository 启用了 CORS 支持。

仓库 REST 控制器方法 CORS 配置​

对于与仓库基础路径共享的自定义 REST 控制器,Spring Data REST 完全支持 Spring Web MVC 的控制器方法配置,如下例所示:

@RepositoryRestController
public class PersonController {

@CrossOrigin(maxAge = 3600)
@RequestMapping(path = "/people/xml/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
public Person retrieve(@PathVariable Long id) {
// …
}
}
备注

使用 @RepositoryRestController 注解的控制器会从其关联的仓库继承 @CrossOrigin 配置。

全局 CORS 配置​

除了基于注解的细粒度配置之外,您可能还希望定义一些全局 CORS 配置。这类似于 Spring Web MVC 的 CORS 配置,但可以在 Spring Data REST 内部声明,并与细粒度的 @CrossOrigin 配置结合使用。默认情况下,允许所有源以及 GET、HEAD 和 POST 方法。

备注

现有的 Spring Web MVC CORS 配置不会应用于 Spring Data REST。

以下示例设置了一个允许的源,添加了 PUT 和 DELETE HTTP 方法,添加并暴露了一些请求头,并将最大存活时间设为一小时:

@Component
public class SpringDataRestCustomization implements RepositoryRestConfigurer {

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {

cors.addMapping("/person/**")
.allowedOrigins("http://domain2.example")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}