SpringSecurity?跨域資源共享(CORS)的實(shí)現(xiàn)
瀏覽器的同源策略(Same-Origin Policy, SOP) 是瀏覽器最核心、最基礎(chǔ)的安全機(jī)制之一,本質(zhì)是為了隔離不同域名的資源,防止惡意網(wǎng)站竊取或篡改其他網(wǎng)站的敏感數(shù)據(jù),保障用戶隱私和網(wǎng)絡(luò)安全。“同源” 指的是兩個(gè)資源的 “協(xié)議(Protocol)、域名(Domain)、端口(Port)” 三者完全一致,缺一不可。只要任意一項(xiàng)不同,就屬于 “跨源(Cross-Origin)”。
CORS(Cross-Origin Resource Sharing)即跨域資源共享,應(yīng)用程序會(huì)通過 CORS(跨域資源共享)機(jī)制來放寬這一嚴(yán)格的(同源)策略,從而允許在特定條件下進(jìn)行跨源請(qǐng)求。在當(dāng)前流行的前后端分離架構(gòu)模式下很可能會(huì)用到 CORS。
創(chuàng)建一個(gè)頁面 src\main\resources\static\index.html,這是一個(gè)靜態(tài)文件,可以直接被訪問,頁面的訪問地址是 http://localhost/index.html,頁面中有一個(gè)按鈕,點(diǎn)擊按鈕的時(shí)候使用 fetch 發(fā)起對(duì) http://localhost/hello 的請(qǐng)求。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="getHelloBtn">get hello</button>
<script>
const getHelloBtn = document.getElementById('getHelloBtn');
getHelloBtn.addEventListener('click', () => {
fetch('http://127.0.0.1/hello')
.then(res => res.text())
.then(data => {
console.log(data);
})
})
</script>
</body>
</html>
因?yàn)轫撁媸褂玫挠蛎?localhost 和接口使用的是 127.0.0.1 IP 地址,域名不一致,所以請(qǐng)求的響應(yīng)被阻止了。

此時(shí)可以通過配置 CORS 就可以來解決這個(gè)同源策略的限制。Spring 提供了 @CrossOrigin 注解,把這個(gè)注解加在控制器上:
@RestController
public class HelloController {
@RequestMapping(value = { "/hello" }, method = RequestMethod.GET)
// 允許 http://localhost 域發(fā)起對(duì)該接口的請(qǐng)求
@CrossOrigin("http://localhost")
public String requestMethodName() {
return "Hello, Spring!";
}
}再次點(diǎn)擊按鈕,瀏覽器控制臺(tái)中打印出了接口響應(yīng)的內(nèi)容:

@CrossOrigin 除了可以用在方法上之外,還可以用在類上,這樣整個(gè)控制器就都允許跨域訪問了。@CrossOrigin 還提供了其他配置參數(shù)
public @interface CrossOrigin {
@AliasFor("origins")
String[] value() default {}; // 允許跨域請(qǐng)求的源
@AliasFor("value")
String[] origins() default {}; // 允許跨域請(qǐng)求的源
String[] originPatterns() default {}; // 通過通配符模式匹配允許的來源
String[] allowedHeaders() default {}; // 指定跨域請(qǐng)求中允許攜帶的請(qǐng)求頭
String[] exposedHeaders() default {}; // 指定跨域響應(yīng)中允許前端讀取的響應(yīng)頭
RequestMethod[] methods() default {}; // 指定允許的 HTTP 請(qǐng)求方法
String allowCredentials() default ""; // 指定是否允許跨域請(qǐng)求攜帶身份憑證,
// 若設(shè)為 true,origins 不能為 *(必須指定具體來源),否則瀏覽器會(huì)拒絕響應(yīng)。
String allowPrivateNetwork() default ""; // 控制是否允許來自私有網(wǎng)絡(luò)(如局域網(wǎng))的跨域請(qǐng)求
long maxAge() default -1L; // 指定預(yù)檢請(qǐng)求(Preflight Request)的結(jié)果緩存時(shí)間(單位:秒)
}通過 @CrossOrigin 注解可以很簡單地解決跨域問題,但需要每個(gè)控制器都要配置一次,就顯得比較啰嗦了,而且一旦需要修改配置工作量就比較大,而且還可能產(chǎn)生一些風(fēng)險(xiǎn)。
Spring Security 也提供了 CORS 的配置,可以進(jìn)行全局的配置:
@Configuration
public class SecurityConfig {
@Resource
private CustomAuthenticationProvider customAuthenticationProvider;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authenticationProvider(customAuthenticationProvider)
.httpBasic(Customizer.withDefaults());
http.csrf(c -> c.disable());
http.cors(c -> {
CorsConfigurationSource source = request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost")); // 允許跨域請(qǐng)求的源
config.setAllowedMethods(Arrays.asList("GET", "POST")); // 指定允許的 HTTP 請(qǐng)求方法
config.setAllowedHeaders(Arrays.asList("*")); // 指定跨域響應(yīng)中允許前端讀取的響應(yīng)頭
return config;
};
c.configurationSource(source);
});
http.authorizeHttpRequests(
auth -> auth
.anyRequest().permitAll());
return http.build();
}
}如果需要不同的路徑有不同的跨域配置,也沒問題:
@Configuration
public class SecurityConfig {
@Resource
private CustomAuthenticationProvider customAuthenticationProvider;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authenticationProvider(customAuthenticationProvider)
.httpBasic(Customizer.withDefaults());
http.csrf(c -> c.disable());
http.cors(c -> {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost"));
config.setAllowedMethods(Arrays.asList("GET"));
config.setAllowedHeaders(Arrays.asList("*"));
source.registerCorsConfiguration("/hello", config); // 給指定的路徑綁定 CORS 配置
CorsConfiguration config2 = new CorsConfiguration();
config2.setAllowedOrigins(Arrays.asList("http://localhost"));
config2.setAllowedMethods(Arrays.asList("POST"));
config2.setAllowedHeaders(Arrays.asList("*"));
source.registerCorsConfiguration("/aa/bb/cc", config2); // 給指定的路徑綁定 CORS 配置
c.configurationSource(source);
});
http.authorizeHttpRequests(
auth -> auth
.anyRequest().permitAll());
return http.build();
}
}到此這篇關(guān)于SpringSecurity 跨域資源共享(CORS)的文章就介紹到這了,更多相關(guān)SpringSecurity 跨域資源共享內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot 快速實(shí)現(xiàn) api 加密的方法
在項(xiàng)目中,為了保證數(shù)據(jù)的安全,我們常常會(huì)對(duì)傳遞的數(shù)據(jù)進(jìn)行加密,常用的加密算法包括對(duì)稱加密(AES)和非對(duì)稱加密(RSA),本文給大家介紹SpringBoot 快速實(shí)現(xiàn) api 加密,感興趣的朋友一起看看吧2023-10-10
Spring Data 2027 動(dòng)態(tài)查詢功能及實(shí)踐
文章主要介紹了SpringData2027中的動(dòng)態(tài)查詢功能,包括QueryByExample、Specification、QueryDSL、CriteriaAPI和動(dòng)態(tài)JPQL等實(shí)現(xiàn)方式,文章詳細(xì)闡述了每種方式的原理、實(shí)踐方法及應(yīng)用場景,并提供了優(yōu)化性能、監(jiān)控調(diào)試和最佳實(shí)踐的建議,最后展望了該功能未來的發(fā)展趨勢2026-04-04
Java與SpringBoot對(duì)redis的使用方式
這篇文章主要介紹了Java與SpringBoot對(duì)redis的使用方式,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08
Java中統(tǒng)計(jì)字符個(gè)數(shù)以及反序非相同字符的方法詳解
本篇文章是對(duì)Java中統(tǒng)計(jì)字符個(gè)數(shù)以及反序非相同字符的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
SpringAop切入點(diǎn)execution表達(dá)式的深入講解
Spring AOP 可能會(huì)經(jīng)常使用 execution切入點(diǎn)指示符,下面這篇文章主要給大家介紹了關(guān)于SpringAop切入點(diǎn)execution表達(dá)式的相關(guān)資料,需要的朋友可以參考下2021-08-08
Spring的RedisTemplate的json反序列泛型丟失問題解決
本文主要介紹了Spring RedisTemplate中使用JSON序列化時(shí)泛型信息丟失的問題及其提出三種解決方案,可以根據(jù)性能需求選擇方案,下面就來具體了解一下2025-07-07
IDEA解決maven包沖突easypoi NoClassDefFoundError的問題
這篇文章主要介紹了IDEA解決maven包沖突easypoi NoClassDefFoundError的問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

