1. CORS 簡介
同源策略(same origin policy)是瀏覽器安全的基石。在同源策略的限制下,非同源的網站之間不能發送 ajax 請求的。
為了解決這個問題,w3c 提出了跨源資源共享,即 CORS(Cross-Origin Resource Sharing)。
CORS 做到了兩點:
- 不破壞即有規則
- 服務器實現了 CORS 接口,就可以跨源通信
基于這兩點,CORS 將請求分為兩類:簡單請求和非簡單請求。
1.1 簡單請求
可以先看下 CORS 出現前的情況:跨源時能夠通過 script 或者 image 標簽觸發 GET 請求或通過表單發送一條 POST 請求,但這兩種請求 HTTP 頭信息中都不能包含任何自定義字段。
簡單請求對應該規則,因此對簡單請求的定義為:
請求方法是 HEAD、GET 或 POST 且 HTTP 頭信息不超過以下幾個字段:Accept、Accept-Language、Content-Language、Last-Event-ID、Content-Type(只限于 application/x-www-form-urlencoded、multipart/form-data、text/plain)。
比如有一個簡單請求:
1
2
3
4
5
|
GET /test HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate, sdch, br Origin: http://www.examples.com Host: www.examples.com |
對于這樣的簡單請求,CORS 的策略是請求時,**在頭信息中添加一個 Origin 字段**,服務器收到請求后,根據該字段判斷是否允許該請求。
- 如果允許,則在 HTTP 頭信息中添加 Access-Control-Allow-Origin 字段,并返回正確的結果
- 如果不允許,則不在頭信息中添加 Access-Control-Allow-Origin 字段。
瀏覽器先于用戶得到返回結果,根據有無 Access-Control-Allow-Origin 字段來決定是否攔截該返回結果。
對于 CORS 出現前的一些服務,CORS 對他們的影響分兩種情況:
- script 或者 image 觸發的 GET 請求不包含 Origin 頭,所以不受到 CORS 的限制,依舊可用。
- 如果是 ajax 請求,HTTP 頭信息中會包含 Origin 字段,由于服務器沒有做任何配置,所以返回結果不會包含 Access-Control-Allow-Origin,因此返回結果會被瀏覽器攔截,接口依舊不可以被 ajax 跨源訪問。
可以看出,CORS 的出現,沒有對”舊的“服務造成任何影響。
另外,除了提到的 Access-Control-Allow-Origin 還有幾個字段用于描述 CORS 返回結果:
- Access-Control-Allow-Credentials: 可選,用戶是否可以發送、處理 cookie。
- Access-Control-Expose-Headers:可選,可以讓用戶拿到的字段。有幾個字段無論設置與否都可以拿到的,包括:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。
1.2 非簡單請求
除了簡單請求之外的請求,就是非簡單請求。
對于非簡單請求的跨源請求,**瀏覽器會在真實請求發出前**,增加一次 OPTION 請求,稱為預檢請求(preflight request)。預檢請求將真實請求的信息,包括請求方法、自定義頭字段、源信息添加到 HTTP 頭信息字段中,詢問服務器是否允許這樣的操作。
比如對于 DELETE 請求:
1
2
3
4
5
|
OPTIONS /test HTTP/1.1 Origin: http://www.examples.com Access-Control-Request-Method: DELETE Access-Control-Request-Headers: X-Custom-Header Host: www.examples.com |
與 CORS 相關的字段有:
- Access-Control-Request-Method: 真實請求使用的 HTTP 方法。
- Access-Control-Request-Headers: 真實請求中包含的自定義頭字段。
服務器收到請求時,需要分別對 Origin、Access-Control-Request-Method、Access-Control-Request-Headers 進行驗證,驗證通過后,會在返回 Http 頭信息中添加
1
2
3
4
5
|
Access-Control-Allow-Origin: http://www.examples.com Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: X-Custom-Header Access-Control-Allow-Credentials: true Access-Control-Max-Age: 1728000 |
他們的含義分別是:
- Access-Control-Allow-Methods: 真實請求允許的方法
- Access-Control-Allow-Headers: 服務器允許使用的字段
- Access-Control-Allow-Credentials: 是否允許用戶發送、處理 cookie
- Access-Control-Max-Age: 預檢請求的有效期,單位為秒。有效期內,不會重復發送預檢請求
當預檢請求通過后,瀏覽器會發送真實請求到服務器。這就實現了跨源請求。
了解完 CORS,接下來我們來搭建簡單的 Spring MVC 服務,并進一步了解 Spring MVC 如何配置 CORS。
2. Spring MVC 環境搭建
打開 http://start.spring.io/,添加 Web Dependency,然后選擇 Generate Project,下載 zip 文件,就得到了一個 spring boot demo。
解壓 zip 文件,雙擊 pom.xml 打開或用 IDEA、Eclipse 將項目按照 maven 導入。
根據 Group、Artifact、Dependencies 填寫的不同,項目目錄結構可能有些許差別,我的項目結構如下:
1
2
3
4
5
6
7
8
9
10
|
├── src │ ├── main/java │ | └── net/xiayule/spring/cors │ | └── SpringBootCorsTestApplication.java | └── resources | ├── static | ├── templates | └── application.properties | └── pom.xml |
我們需要關心的只有 SpringBootCorsTestApplication.java。在 SpringBootCorsTestApplication.java 添加以下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@RestController @SpringBootApplication public class SpringBootCorsTestApplication { @RequestMapping (value = "/test" ) public String greetings() { return "{\"project\":\"just a test\"}" ; } public static void main(String[] args) { SpringApplication.run(SpringBootCorsTestApplication. class , args); } } |
@RequestMapping(value = "/test")
的含義是該方法接受來自 /test 的請求,并且提供了對 HTTP 的 GET、POST、DELETE 等方法的支持。
運行項目的方法為,在項目根目錄執行 mvn spring-boot:run 啟動應用,打開瀏覽器訪問 http://localhost:8080 即可看到效果:
后端服務搭建好了,接著實現前端。為了簡單,直接創建一個 test.html 文件,添加以下內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<!DOCTYPE html> < html > < head > < title >Hello CORS</ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></ script > < script > $(document).ready(function() { $.ajax({ url: "http://localhost:8080/test", method: "POST", contentType: "application/json; charset=utf-8" }).then(function(data, status, jqxhr) { alert(data) }); }); </ script > </ head > < body > </ body > </ html > |
使用瀏覽器打開該文件,就會觸發一條向 http://localhost:8080 的請求。可以通過修改上面代碼的 method,來觸發不同類型的請求。
由于是直接使用瀏覽器打開,**網頁的源為 null**, 當向源 http://localhost:8080 請求時,就變成了跨源請求,因此如果后端不加 CORS 的配置,返回的 HTTP 頭信息中不會包含 Access-Control-Allow-Origin,因此瀏覽器會報出如下錯誤:
3. 配置 CORS
一個應用可能會有多個 CORS 配置,并且可以設置每個 CORS 配置針對一個接口或一系列接口或者對所有接口生效。
舉例來說,我們需要:
- 讓 /test 接口支持跨源訪問,而 /test/1 或 /api 等其它接口不支持跨源訪問
- 讓 /test/* 這一類接口支持跨源訪問,而 /api 等其它接口不支持跨源訪問
- 站點所有的接口都支持跨源訪問
對第一種情況,如果想要對某一接口配置 CORS,可以在方法上添加 CrossOrigin 注解:
1
2
3
4
5
|
@CrossOrigin (origins = { "http://localhost:9000" , "null" }) @RequestMapping (value = "/test" , method = RequestMethod.GET) public String greetings() { return "{\"project\":\"just a test\"}" ; } |
第二種情況,如果想對一系列接口添加 CORS 配置,可以在類上添加注解,對該類聲明所有接口都有效:
1
2
3
4
5
6
|
CrossOrigin(origins = { "http://localhost:9000" , "null" }) @RestController @SpringBootApplication public class SpringBootCorsTestApplication { // xxx } |
第三種情況,添加全局配置,則需要添加一個配置類:
1
2
3
4
5
6
7
8
9
10
11
12
|
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping( "/**" ) .allowedOrigins( "http://localhost:9000" , "null" ) .allowedMethods( "POST" , "GET" , "PUT" , "OPTIONS" , "DELETE" ) .maxAge( 3600 ) .allowCredentials( true ); } } |
另外,還可以通過添加 Filter 的方式,配置 CORS 規則,并手動指定對哪些接口有效。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials( true ); config.addAllowedOrigin( "http://localhost:9000" ); config.addAllowedOrigin( "null" ); config.addAllowedHeader( "*" ); config.addAllowedMethod( "*" ); source.registerCorsConfiguration( "/**" , config); // CORS 配置對所有接口都有效 FilterRegistrationBean bean = newFilterRegistrationBean( new CorsFilter(source)); bean.setOrder( 0 ); return bean; } |
4. 實現剖析
無論是通過哪種方式配置 CORS,其實都是在構造 CorsConfiguration。
一個 CORS 配置用一個 CorsConfiguration 類來表示,它的定義如下:
1
2
3
4
5
6
7
8
|
public class CorsConfiguration { private List<String> allowedOrigins; private List<String> allowedMethods; private List<String> allowedHeaders; private List<String> exposedHeaders; private Boolean allowCredentials; private Long maxAge; } |
Spring MVC 中對 CORS 規則的校驗,都是通過委托給 DefaultCorsProcessor 實現的。
DefaultCorsProcessor 處理過程如下:
- 判斷依據是 Header 中是否包含 Origin。如果包含則說明為 CORS 請求,轉到 2;否則,說明不是 CORS 請求,不作任何處理。
- 判斷 response 的 Header 是否已經包含 Access-Control-Allow-Origin,如果包含,證明已經被處理過了, 轉到 3,否則不再處理。
- 判斷是否同源,如果是則轉交給負責該請求的類處理
- 是否配置了 CORS 規則,如果沒有配置,且是預檢請求,則拒絕該請求,如果沒有配置,且不是預檢請求,則交給負責該請求的類處理。如果配置了,則對該請求進行校驗。
校驗就是根據 CorsConfiguration 這個類的配置進行判斷:
- 判斷 origin 是否合法
- 判斷 method 是否合法
- 判斷 header 是否合法
- 如果全部合法,則在 response header 中添加響應的字段,并交給負責該請求的類處理,如果不合法,則拒絕該請求。
5. 總結
本文介紹了 CORS 的知識以及如何在 Spring MVC 中配置 CORS。希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.coding.net/blog/spring-mvc-cors