簡體   English   中英

Spring @RestController是否默認啟用CORS?

[英]Does Spring @RestController enable CORS by default?

我正在閱讀此Spring安全性教程 ,它提到我們可能會看到2個針對動態資源的請求,因為此控制器進行了CORS協商:

    @SpringBootApplication
    @RestController
    public class UiApplication {

      @RequestMapping("/resource")
      public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
      }

      public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
      }

    }

只是好奇@RestController批注是否默認啟用CORS?

不行

你需要自己添加@CrossOrigin注解讓春CORS支持。

為什么:

默認情況下啟用CORS( 跨域資源共享 )將是一個嚴重的安全問題

考慮來自官方文檔的此示例。

出於安全原因,瀏覽器禁止AJAX調用當前來源之外的資源。 例如,當您在一個標簽中檢查銀行帳戶時 ,可以在另一個標簽中打開evil.com網站。 從evil.com腳本應該使用您的憑據能夠使AJAX請求您的銀行API(例如,從您的帳戶中取錢的 !)。

不,請參見https://spring.io/guides/gs/rest-service-cors/

為了使RESTful Web服務的響應中包含CORS訪問控制標頭,您只需向處理程序方法添加@CrossOrigin批注:

@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
   System.out.println("==== in greeting ====");
   return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

默認情況下,CORS支持是禁用的,只有在設置了endpoints.cors.allowedorigins屬性后才啟用。 以下配置允許來自example.com域的GET和POST調用:

endpoints.cors.allowed-origins=http://example.com
endpoints.cors.allowed-methods=GET,POST

Spring Boot參考指南。

檢查EndpointCorsProperties以獲取選項的完整列表。

不能。例如,evil.com的腳本不能向您的銀行發出AJAX請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM