Spring框架中的跨域CORS配置的完整教學(xué)
什么是跨域CORS
CORS(Cross-Origin Resource Sharing,跨域資源共享)是一種機(jī)制,允許在瀏覽器中向不同源(域名、協(xié)議或端口不同)的服務(wù)器發(fā)起請求。在Web開發(fā)中,出于安全考慮,瀏覽器會(huì)實(shí)施同源策略(Same-Origin Policy),限制從一個(gè)源加載的文檔或腳本與另一個(gè)源的資源進(jìn)行交互。CORS機(jī)制提供了一種安全的方式來實(shí)現(xiàn)跨域訪問。
Spring中的CORS配置方法
1. 全局CORS配置
使用WebMvcConfigurer配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允許所有路徑
.allowedOrigins("*") // 允許所有來源,生產(chǎn)環(huán)境應(yīng)限制具體域名
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允許的HTTP方法
.allowedHeaders("*") // 允許所有請求頭
.exposedHeaders("Authorization") // 暴露的響應(yīng)頭
.allowCredentials(true) // 允許攜帶憑證(cookie)
.maxAge(3600); // 預(yù)檢請求結(jié)果緩存時(shí)間(秒)
}
}
Spring Boot 2.7+ 方式
從Spring Boot 2.7開始,推薦使用CorsFilter而不是WebMvcConfigurer:
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 設(shè)置允許的源
config.addAllowedOrigin("*");
// 設(shè)置允許的HTTP方法
config.addAllowedMethod("*");
// 設(shè)置允許的請求頭
config.addAllowedHeader("*");
// 設(shè)置允許攜帶憑證
config.setAllowCredentials(true);
// 設(shè)置暴露的響應(yīng)頭
config.addExposedHeader("Authorization");
// 設(shè)置預(yù)檢請求結(jié)果緩存時(shí)間
config.setMaxAge(3600L);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
2. 控制器級別CORS配置
使用@CrossOrigin注解可以在控制器類或方法級別配置CORS:
// 控制器類級別配置
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ApiController {
@GetMapping("/data")
public ResponseEntity<String> getData() {
return ResponseEntity.ok("Data response");
}
}
// 方法級別配置
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/data")
@CrossOrigin(origins = "http://localhost:3000",
allowedHeaders = "*",
methods = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<String> getData() {
return ResponseEntity.ok("Data response");
}
}
3. 基于過濾器的CORS配置
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// 設(shè)置CORS響應(yīng)頭
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
// 處理預(yù)檢請求
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
}
}
Spring Security環(huán)境下的CORS配置
當(dāng)使用Spring Security時(shí),CORS配置需要與Security配置集成:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 添加CORS配置
.cors().and()
// 禁用CSRF(如果需要)
.csrf().disable()
// 其他安全配置...
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated();
}
// 注入CORS配置Bean
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
生產(chǎn)環(huán)境CORS最佳實(shí)踐
限制允許的源:不要在生產(chǎn)環(huán)境使用"*"通配符,而應(yīng)該指定具體的前端域名:
config.setAllowedOrigins(Arrays.asList("https://www.example.com", "https://app.example.com"));
謹(jǐn)慎使用credentials:如果設(shè)置了allowCredentials = true,allowedOrigins不能使用"*"通配符。
限制允許的HTTP方法:只允許應(yīng)用程序需要的HTTP方法,而不是全部:
config.setAllowedMethods(Arrays.asList("GET", "POST"));
限制允許的請求頭:只允許必要的請求頭,提高安全性。
設(shè)置適當(dāng)?shù)膍axAge:避免頻繁的預(yù)檢請求,減少服務(wù)器負(fù)擔(dān)。
常見問題及解決方案
CORS策略阻止了請求
- 檢查服務(wù)器是否正確設(shè)置了
Access-Control-Allow-Origin頭 - 確保請求的方法和頭在允許列表中
預(yù)檢請求失敗
- 確保服務(wù)器正確處理了
OPTIONS請求 - 檢查是否配置了
maxAge參數(shù)
憑證模式的問題
- 當(dāng)使用
withCredentials: true時(shí),服務(wù)端必須指定明確的Access-Control-Allow-Origin值 - 不能使用通配符
*
通過以上配置方法,可以根據(jù)項(xiàng)目需求靈活地實(shí)現(xiàn)Spring應(yīng)用中的CORS支持,確保前端應(yīng)用能夠安全地進(jìn)行跨域資源訪問。
到此這篇關(guān)于Spring框架中的跨域CORS配置的完整教學(xué)的文章就介紹到這了,更多相關(guān)Spring 跨域CORS配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot整合Keycloak的項(xiàng)目實(shí)踐
本文介紹了如何設(shè)置了Keycloak 服務(wù)器及在SpringBoot中使用 Spring Security OAuth2.0結(jié)合Keycloak實(shí)現(xiàn)認(rèn)證和授權(quán),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2026-01-01
在Spring Boot中使用Spring-data-jpa實(shí)現(xiàn)分頁查詢
如何使用jpa進(jìn)行多條件查詢以及查詢列表分頁呢?下面我將介紹兩種多條件查詢方式。具體實(shí)例代碼大家參考下本文吧2017-07-07
使用Java實(shí)現(xiàn)通用樹形結(jié)構(gòu)構(gòu)建工具類
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)通用樹形結(jié)構(gòu)構(gòu)建工具類,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03
Java實(shí)現(xiàn)一鍵獲取Mysql所有表字段設(shè)計(jì)和建表語句的工具類
這篇文章主要為大家詳細(xì)介紹了如何利用Java編寫一個(gè)工具類,可以實(shí)現(xiàn)一鍵獲取Mysql所有表字段設(shè)計(jì)和建表語句,感興趣的小伙伴可以了解一下2023-05-05
Eclipse+Java+Swing+Mysql實(shí)現(xiàn)電影購票系統(tǒng)(詳細(xì)代碼)
這篇文章主要介紹了Eclipse+Java+Swing+Mysql實(shí)現(xiàn)電影購票系統(tǒng)并附詳細(xì)的代碼詳解,需要的小伙伴可以參考一下2022-01-01
SpringBoot配置文件properties和yml的實(shí)現(xiàn)
本文主要介紹了SpringBoot配置文件properties和yml的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
Java中使用數(shù)組實(shí)現(xiàn)棧數(shù)據(jù)結(jié)構(gòu)實(shí)例
這篇文章主要介紹了Java中使用數(shù)組實(shí)現(xiàn)棧數(shù)據(jù)結(jié)構(gòu)實(shí)例,本文先是講解了實(shí)現(xiàn)棧至少應(yīng)該包括以下幾個(gè)方法等知識,然后給出代碼實(shí)例,需要的朋友可以參考下2015-01-01

