什么是跨域?
- 當一個請求url的協(xié)議、域名、端口三者之間任意一個與當前頁面url不同即為跨域
- 瀏覽器同源策略的限制
為什么會有同源策略?
- 為了安全
- 如果沒有同源策略,不同源的數(shù)據(jù)和資源(如HTTP頭、Cookie、DOM、localStorage等)就能相互隨意訪問,沒有安全性可言
springboot項目解決跨域的方式
添加webMvc配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
- 優(yōu)點: 全局配置比較方便
- 缺點:定制化比較麻煩,針對性比較弱
- 適用場景:全局化配置
添加web全局過濾器
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
- 優(yōu)點: 針對性強,可從ServletRequest拿到特定的數(shù)據(jù),針對性的支持跨域
- 缺點:要配置的數(shù)據(jù)比較多,配置中的一些配置項要主要選擇,謹慎選擇
- 適用場景:保證數(shù)據(jù)安全,針對特定的域名支持跨域訪問
springboot 注解形式
@RequestMapping("/test")
@CrossOrigin
public String test(){
return "hello Spring-boot";
}
- 優(yōu)點: 比較優(yōu)雅,一個注解搞定,針對性強,可具體到某個方法
- 缺點:定制化比較弱
- 適用場景:某個類或某些方法只允許特定域名進行跨域訪問
服務端解決跨域流程分析
- 瀏覽器將CORS請求分成兩類:簡單請求(simple request)和非簡單請求(not-so-simple request),兩者的處理方式不一樣
- 同時滿足以下兩種條件的就屬于簡單請求
* 請求方法是以下三種方法之一:get head post
* HTTP的頭信息不超出以下幾種字段:Accept Accept-Language Content-Language Last-Event-ID Content-Type:只限于三個值application/x-www-form-urlencoded、multipart/form-data、text/plain
- 當請求存在跨域資源共享(CORS)并且是非簡單請求,就會觸發(fā)CORS的預檢請求,"預檢"請求用的請求方法是OPTIONS
- 下面用一個具體的案例來分析服務端是如何解決跨域問題
- 先來一個簡單請求:在http://abc.com域下請求http://abc.com:8080的接口 請求頭信息什么都不帶
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</header>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script >
const httpHandler = axios.create({
headers: {
},
});
httpHandler.get('http://abc.com:8080/test')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
<body>
刷新頁面
</body>
01.png
- 可以看到請求頭什么沒帶的情況下第一次請求(針對服務端而言)就會直接返回接口數(shù)據(jù)
02.png
- 變成一個非簡單請求攜帶了一個請求頭信息
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</header>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script >
axios.defaults.withCredentials = true;
const httpHandler = axios.create({
headers: {
"Token":"123456"
},
});
httpHandler.get('http://abc.com:8080/test')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
<body>
測試
</body>
第一次預請求
03.png
04.png
第二次請求
05.png
06.png
可以看到第一次請求與第二次請求的區(qū)別
- 瀏覽器先詢問服務器,當前網(wǎng)頁所在的域名是否在服務器的許可名單之中,以及可以使用哪些HTTP動詞和頭信息字段。只有得到肯定答復,瀏覽器才會發(fā)出正式的XMLHttpRequest請求
服務器收到"預檢"請求以后,檢查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后,確認允許跨源請求,就可以做出回應
-
一旦服務器通過了"預檢"請求,以后每次瀏覽器正常的CORS請求,就都跟簡單請求一樣,會有一個Origin頭信息字段。服務器的回應,也都會有一個Access-Control-Allow-Origin頭信息字段
c9274cfc325ebccb9148b07eea03aa8.png
總結
1.為了保證數(shù)據(jù)安全才有了同源策略,從而有了跨域的概念
2.springBoot多種配置方式支持跨域,合理按需選擇
3.支持跨域在服務端請求有簡單請求和非簡單請求的區(qū)別,非簡單請求需要有一次預檢請求的訪問