解決SpringBoot跨域的三種方式
出于瀏覽器的同源策略限制。同源策略(Sameoriginpolicy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響。可以說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。同源策略會阻止一個域的javascript腳本和另外一個域的內容進行交互。所謂同源(即指在同一個域)就是兩個頁面具有相同的協議(protocol),主機(host)和端口號(port)
簡單說A應用只能訪問A應用后臺傳來數據,B應用只能訪問B應用后臺傳來的數據,如果A應用用Ajax獲取數據時的URL地址中的協議、端口、域名其中有一個和B應用對應的話,則是A應用跨域了想獲取B應用數據,是不允許的
1.2、什么是跨域當一個請求url的 協議、域名、端口 三者之間任意一個與當前頁面url不同即為跨域
當前頁面URL 被請求頁面URL 是否跨域 原因 http://www.test.com/ http://www.test.com/index.html 否 同源(協議、域名、端口號相同) http://www.test.com/ https://www.test.com/index.html 跨域 協議不同(http/https) http://www.test.com/ http://www.baidu.com/ 跨域 主域名不同(test/baidu) http://www.test.com/ http://blog.test.com/ 跨域 子域名不同(www/blog) http://www.test.com:8080/ http://www.test.com:7001/ 跨域 端口號不同(8080/7001) 1.3、非同源限制瀏覽器為了安全性,限制了一些請求無法訪問非同源URL
【1】無法讀取非同源網頁的 Cookie、LocalStorage 和 IndexedDB【2】無法接觸非同源網頁的 DOM【3】無法向非同源地址發送 AJAX 請求
1.4、如何解決跨域問題服務端使用純代碼的方式邏輯解決跨域問題,如果使用SpringBoot的話請看下章
【騰訊文檔】JSONP跨域解決 https://docs.qq.com/doc/DVEVTemdrcVVjSFlE
二、SpringBoot解決跨域問題①:返回新的CorsFilter
②:重寫WebMvcConfigurer
③:使用注解@CrossOrigin
注意:CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,對應springBoot 1.3版本以上上面前兩種方式屬于全局 CORS 配置,后兩種屬于局部 CORS配置。如果使用了局部跨域是會覆蓋全局跨域的規則,所以可以通過 @CrossOrigin 注解來進行細粒度更高的跨域資源控制。其實無論哪種方案,最終目的都是修改響應頭,向響應頭中添加瀏覽器所要求的數據,進而實現跨域
2.1、配置CorsFilter(全局跨域)import org.springframework.boot.SpringBootConfiguration;import org.springframework.context.annotation.Bean;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@SpringBootConfigurationpublic class WebGlobalConfig { @Bean public CorsFilter corsFilter() {//創建CorsConfiguration對象后添加配置CorsConfiguration config = new CorsConfiguration();//設置放行哪些原始域config.addAllowedOrigin('*');//放行哪些原始請求頭部信息config.addAllowedHeader('*');//暴露哪些頭部信息config.addExposedHeader('*');//放行哪些請求方式config.addAllowedMethod('GET'); //getconfig.addAllowedMethod('PUT'); //putconfig.addAllowedMethod('POST'); //postconfig.addAllowedMethod('DELETE'); //delete//corsConfig.addAllowedMethod('*'); //放行全部請求//是否發送Cookieconfig.setAllowCredentials(true);//2. 添加映射路徑UrlBasedCorsConfigurationSource corsConfigurationSource =new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration('/**', config);//返回CorsFilterreturn new CorsFilter(corsConfigurationSource); }}
如果你使用的是高版本SpringBoot2.4.4則需要改動一下,否則后臺報錯
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value '*' since that cannot be set on the 'Access-Control-Allow-Origin' response header. To allow credentials to a set of origins, list them explicitly or consider using 'allowedOriginPatterns' instead.at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) ~[spring-web-5.3.6.jar:5.3.6]
當allowCredentials為true時,alloedOrigins不能包含特殊值“*”,因為該值不能在“Access-Control-Allow-Origin”響應頭部中設置。要允許憑據訪問一組來源,請顯式列出它們或考慮改用“AllowedOriginPatterns”。
解決:把config.addAllowedOrigin('*'); 替換成config.addAllowedOriginPattern('*');
2.2、重寫WebMvcConfigurer(全局跨域)import org.springframework.boot.SpringBootConfiguration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@SpringBootConfigurationpublic class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) {//添加映射路徑registry.addMapping('/**')//是否發送Cookie.allowCredentials(true)//設置放行哪些原始域 SpringBoot2.4.4下低版本使用.allowedOrigins('*') .allowedOriginPatterns('*')//放行哪些請求方式.allowedMethods(new String[]{'GET', 'POST', 'PUT', 'DELETE'})//.allowedMethods('*') //或者放行全部//放行哪些原始請求頭部信息.allowedHeaders('*')//暴露哪些原始請求頭部信息.exposedHeaders('*'); }}2.3、使用注解@CrossOrigin(局部跨域)
@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface CrossOrigin { //這origins和value是一樣的 //允許來源域名的列表,例如 ’www.jd.com’,匹配的域名是跨域預請求 Response 頭中的’Access-Control-Aloow_origin’ //字段值。不設置確切值時默認支持所有域名跨域訪問。 @AliasFor('origins') String[] value() default {}; @AliasFor('value') String[] origins() default {}; //高版本下Spring2.4.4使用originPatterns 而不是value 和 origins String[] originPatterns() default {}; //跨域請求中允許的請求頭中的字段類型, 該值對應跨域預請求 Response 頭中的 ’Access-Control-Allow-Headers’ 字段值。 //不設置確切值默認支持所有的header字段(Cache-Controller、Content-Language、Content-Type、 //Expires、Last-Modified、Pragma)跨域訪問 String[] allowedHeaders() default {}; //跨域請求請求頭中允許攜帶的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、 //Pragma這六個基本字段之外的其他字段信息,對應的是跨域請求 Response 頭中的 ’Access-control-Expose-Headers’字段值 String[] exposedHeaders() default {}; //跨域HTTP請求中支持的HTTP請求類型(GET、POST...),不指定確切值時默認與 Controller 方法中的 methods 字段保持一致。 RequestMethod[] methods() default {}; //該值對應的是是跨域請求 Response 頭中的 ’Access-Control-Allow-Credentials’ 字段值。 //瀏覽器是否將本域名下的 cookie 信息攜帶至跨域服務器中。默認攜帶至跨域服務器中,但要實現 cookie //共享還需要前端在 AJAX 請求中打開 withCredentials 屬性。 String allowCredentials() default ''; //該值對應的是是跨域請求 Response 頭中的 ’Access-Control-Max-Age’ 字段值,表示預檢請求響應的緩存持續的最大時間, //目的是減少瀏覽器預檢請求/響應交互的數量。默認值1800s。設置了該值后,瀏覽器將在設置值的時間段內對該跨域請求不再發起預請求 long maxAge() default -1;}
①:在控制器(類上)使用@CrossOrigin注解,表示該類的所有方法允許跨域
@Controller@RequestMapping('/shop')@CrossOrigin(originPatterns = '*', methods = {RequestMethod.GET, RequestMethod.POST})public class ShopController {@GetMapping('/') @ResponseBody public Map<String, Object> findAll() {//返回數據return DataSchool.getStudents(); }}
②:我們也可以設置更小的粒度,在方法上設置跨域
@Controller@RequestMapping('/shop')public class ShopController { @GetMapping('/') @ResponseBody //更小的解決跨域 設置只能某些地址訪問 @CrossOrigin(originPatterns = 'http://localhost:8080') public Map<String, Object> findAll() {//返回數據return DataSchool.getStudents(); }}
以上就是解決SpringBoot跨域的三種方式的詳細內容,更多關于SpringBoot跨域的資料請關注好吧啦網其它相關文章!
相關文章:
