溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot解決跨域請求攔截問題代碼實例

發(fā)布時間:2020-08-31 13:21:17 來源:腳本之家 閱讀:135 作者:冬眠的山谷 欄目:編程語言

前言

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

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

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

注意兩點:

1.必須是腳本請求,比如AJAX請求。

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

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

2.跨域攔截是前端請求已經發(fā)出,并且在后端返回響應時檢查相關參數,是否允許接收后端請求。

在微服務開發(fā)中,一個系統(tǒng)包含多個微服務,會存在跨域請求的場景。

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

搭建項目

這里創(chuàng)建兩個web項目,web1 和 web2.

web2項目請求web1項目的資源。

這里只貼關鍵代碼,完整代碼參考GitHub

WEB2

創(chuàng)建一個Controller返回html頁面

@Slf4j
@Controller
public class HomeController {
@RequestMapping("/index")
public String home(){
log.info("/index");
return "/home";
}
}

html頁面 home.html

這里創(chuàng)建了一個按鈕,按鈕按下則請求資源: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狀態(tài): " + 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");
}
}

再次訪問將會返回正常數據。

SpringBoot解決跨域請求攔截問題代碼實例

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

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

SpringBoot解決跨域請求攔截問題代碼實例

同時還可以使用注解 @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;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI