Springboot 跨域


SpringBoot跨域 

一:什么是跨域

1:為什么會出現跨域問題

  出於瀏覽器的同源策略限制。同源策略(Sameoriginpolicy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響。可以說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。同源策略會阻止一個域的javascript腳本和另外一個域的內容進行交互。所謂同源(即指在同一個域)就是兩個頁面具有相同的協議(protocol),主機(host)和端口號(port)

  簡單說A應用只能訪問A應用后台傳來數據,B應用只能訪問B應用后台傳來的數據,如果A應用用Ajax獲取數據時的URL地址中的協議、端口、域名其中有一個和B應用對應的話,則是A應用跨域了想獲取B應用數據,是不允許的

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)
跨域流程

3:非同源限制

瀏覽器為了安全性,限制了一些請求無法訪問非同源URL

【1】無法讀取非同源網頁的 Cookie、LocalStorage 和 IndexedDB
【2】無法接觸非同源網頁的 DOM
【3】無法向非同源地址發送 AJAX 請求

4:如何解決跨域問題

  服務端使用純代碼的方式邏輯解決跨域問題,如果使用SpringBoot的話請看下章

   【騰訊文檔】JSONP跨域解決   https://docs.qq.com/doc/DVEVTemdrcVVjSFlE

二:SpringBoot解決跨域問題

復制代碼
五種解決方式: ①:返回新的CorsFilter ②:重寫WebMvcConfigurer ③:使用注解@CrossOrigin ④:手動設置響應頭(HttpServletResponse)參考第一章第四節
注意: CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,對應springBoot 1.3版本以上 上面前兩種方式屬於全局 CORS 配置,后兩種屬於局部 CORS配置。如果使用了局部跨域是會覆蓋全局跨域的規則,
所以可以通過 @CrossOrigin 注解來進行細粒度更高的跨域資源控制。 其實無論哪種方案,最終目的都是修改響應頭,向響應頭中添加瀏覽器所要求的數據,進而實現跨域
復制代碼

響應頭信息

• Access-Control-Allow-Origin:支持哪些來源的請求跨域
• Access-Control-Allow-Methods:支持哪些方法跨域
• Access-Control-Allow-Credentials:跨域請求默認不包含cookie,設置為true可以包含cookie
• Access-Control-Expose-Headers:跨域請求暴露的字段
  •CORS請求時,XMLHttpRequest對象的getResponseHeader()方法只能拿到6個基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必須在Access-Control-                      Expose-Headers里面指定。
•Access-Control-Max-Age:表明該響應的有效時間為多少秒。在有效時間內,瀏覽器無須為同一請求再次發起預檢請求。請注意,瀏覽器自身維護了一個最大有效時間,如果該首部字段的值超過了最大有效時間,將不會生效

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;

/**
 * @Author AnHui_XiaoYang
 * @Email 939209948@qq.com
 * @Date 2021/5/10 17:07
 * @Description 
 */
@SpringBootConfiguration
public class WebGlobalConfig {

    @Bean
    public CorsFilter corsFilter() {

        //創建CorsConfiguration對象后添加配置
        CorsConfiguration config = new CorsConfiguration();
        //設置放行哪些原始域
       config.addAllowedOrigin("*"); //放行哪些原始請求頭部信息
        config.addAllowedHeader("*");
        //暴露哪些頭部信息
        config.addExposedHeader("*");
        //放行哪些請求方式
        config.addAllowedMethod("GET");     //get
        config.addAllowedMethod("PUT");     //put
        config.addAllowedMethod("POST");    //post
        config.addAllowedMethod("DELETE");  //delete
        //corsConfig.addAllowedMethod("*");     //放行全部請求

        //是否發送Cookie
        config.setAllowCredentials(true);

        //2. 添加映射路徑
        UrlBasedCorsConfigurationSource corsConfigurationSource =
                new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        //返回CorsFilter
        return 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:重寫WebMvcConfigurer(全局跨域)

復制代碼
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Author AnHui_XiaoYang
 * @Email 939209948@qq.com
 * @Date 2021/5/10 17:49
 * @Description
 */
@SpringBootConfiguration
public 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("*");
    }
}
復制代碼

3:使用注解@CrossOrigin(局部跨域)

復制代碼
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @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();
    }
}
復制代碼

4:創建一個 filter 解決跨域

@Slf4j
@Component
@WebFilter(urlPatterns = { "/*" }, filterName = "headerFilter")
public class HeaderFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp;
        //解決跨域訪問報錯
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        //設置過期時間
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        // 支持HTTP 1.1.
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        // 支持HTTP 1.0. response.setHeader("Expires", "0");
        response.setHeader("Pragma", "no-cache");
        // 編碼
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("跨域過濾器啟動");
    }

    @Override
    public void destroy() {
        log.info("跨域過濾器銷毀");
    }
}

5:重寫WebMvcConfigurer(全局跨域)

package com.stu.infrastructure.confing;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.util.pattern.PathPatternParser;

/******************************
 * 用途說明:
 * 作者姓名: Administrator
 * 創建時間: 2022-07-27 23:16
 ******************************/
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // #允許向該服務器提交請求的URI,*表示全部允許,在SpringMVC中,如果設成*,會自動轉成當前請求頭中的Origin
        config.addAllowedOrigin("*");
        // #允許訪問的頭信息,*表示全部
        config.addAllowedHeader("*");
        // 允許提交請求的方法類型,*表示全部允許
        config.addAllowedMethod("*");

        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source =
                new org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

}

6:重寫WebMvcConfigurer(全局跨域)

package com.stu.study.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


/******************************
 * 用途說明:
 * 作者姓名: Administrator
 * 創建時間: 2022-07-27 23:16
 ******************************/
@Configuration
public class CorsConfig {
    // 當前跨域請求最大有效時長。這里默認1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 設置訪問源地址
        corsConfiguration.addAllowedHeader("*"); // 2 設置訪問源請求頭
        corsConfiguration.addAllowedMethod("*"); // 3 設置訪問源請求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 對接口配置跨域設置
        return new CorsFilter(source);
    }

}

 

 

 

參考:
https://www.cnblogs.com/antLaddie/
https://mp.weixin.qq.com/s/3t-_lJu47tIUBnLIpghMFg
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM