1. 程式人生 > >SpringBoot解決跨域請求攔截

SpringBoot解決跨域請求攔截

 

前言 

同源策略:判斷是否是同源的,主要看這三點,協議,ip,埠。

同源策略就是瀏覽器出於網站安全性的考慮,限制不同源之間的資源相互訪問的一種政策。

比如在域名https://www.baidu.com下,指令碼不能夠訪問https://www.sina.com源下的資源,否則將會被瀏覽器攔截。

 

注意兩點:

1.必須是指令碼請求,比如AJAX請求。

但是如下情況不會產生跨域攔截

<img src="xxx"/>
<a href='xxx"> </a>

2.跨域攔截是前端請求已經發出,並且在後端返回響應時檢查相關引數,是否允許接收後端請求。

 

 在微服務開發中,一個系統包含多個微服務,會存在跨域請求的場景。

 

本文主要講解SpringBoot解決跨域請求攔截的問題。

 

搭建專案

這裡建立兩個web專案,web1 和 web2.

web2專案請求web1專案的資源。

這裡只貼關鍵程式碼,完整程式碼參考GitHub

WEB2

建立一個Controller返回html頁面

@Slf4j
@Controller
public class HomeController {

    @RequestMapping("/index")
    public String home(){
        log.info("/index");

        return "/home";
    }
}

 

html頁面 home.html

這裡建立了一個按鈕,按鈕按下則請求資源:"http://localhost:8301/hello"

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>web2</title>

    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </script>

    <script>
        $(function () {
            
            $("#testBtn").click(function () {
                console.log("testbtn ...");
                $.get("http://localhost:8301/hello",function(data,status){
                    alert("資料: " + data + "\n狀態: " + status);
                });
            })
            
        })

    </script>
</head>
<body>
    web2
    <button id="testBtn">測試</button>
</body>
</html>

 

WEB1

@Slf4j
@RestController
public class Web1Controller {

    @RequestMapping("/hello")
    public String hello(){
        log.info("hello ");
        return "hello," + new Date().toString();
    }
}

 這裡配置兩個專案為不同的埠。

WEB1為8301

WEB2為8302

因此是不同源的。 

測試

在web1還沒有配置允許跨域訪問的情況下

按下按鈕,將會出現錯誤。顯示Header中沒有Access-Control-Allow-Origin

Access to XMLHttpRequest at 'http://localhost:8301/hello' from origin 'http://localhost:8300' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

 

WEB1新增允許跨域請求,通過實現WebMvcConfigurer

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/hello");
    }
}

 

再次訪問將會返回正常資料。

除了以上的配置外,還可以做更細緻的限制

比如對請求的headers,請求的方法POST/GET...。請求的源進行限制。

 

同時還可以使用註解 @CrossOrigin來替換上面的配置。

@Slf4j
@RestController
public class Web1Controller {

    @CrossOrigin
    @RequestMapping("/hello")
    public String hello(){
        log.info("hello ");
        return "hello," + new Date().toString();
    }
}

 

 

註解可以用在類上,也可以用在方法上,但必須是控制器類

配置和上面一樣,也是可以對方法,header,源進行個性化限制。

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
    /** @deprecated */
    @Deprecated
    String[] DEFAULT_ORIGINS = new String[]{"*"};
    /** @deprecated */
    @Deprecated
    String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"};
    /** @deprecated */
    @Deprecated
    boolean DEFAULT_ALLOW_CREDENTIALS = false;
    /** @deprecated */
    @Deprecated
    long DEFAULT_MAX_AGE = 1800L;

    @AliasFor("origins")
    String[] value() default {};

    @AliasFor("value")
    String[] origins() default {};

    String[] allowedHeaders() default {};

    String[] exposedHeaders() default {};

    RequestMethod[] methods() default {};

    String allowCredentials() default "";

    long maxAge() default -1L;
}

&n