設定 CORS

基於安全考量,瀏覽器禁止對當前來源以外的資源發出 AJAX 呼叫。當使用瀏覽器發出的客戶端 HTTP 請求時,您會希望啟用對特定 HTTP 資源的存取權限。

Spring Data REST 從 2.6 版本開始,透過 Spring 的 CORS 支援,支援跨來源資源共享 (CORS)。

Repository 介面 CORS 設定

您可以在您的 repository 介面中新增 @CrossOrigin 註解,為整個 repository 啟用 CORS。預設情況下,@CrossOrigin 允許所有來源和 HTTP 方法。以下範例展示了跨來源 repository 介面定義

@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 支援。

Repository REST 控制器方法 CORS 設定

Spring Data REST 完全支援 Spring Web MVC 在自訂 REST 控制器上的控制器方法設定,這些控制器共享 repository 基礎路徑,如下列範例所示

@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 註解的控制器會從其相關聯的 repository 繼承 @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);
  }
}