SpringBoot中處理跨域資源的5種實現(xiàn)方法與對比
在 Spring Boot 中處理跨域資源共享(CORS)問題,有多種解決方案。以下是幾種常見的方法:
方法1:在控制器或方法上添加 @CrossOrigin 注解(推薦)
@RestController
@CrossOrigin(origins = "*") // 允許所有源
// 或者指定特定源:@CrossOrigin(origins = "http://localhost:3000")
public class PrintController {
@PostMapping(value = "/v1/multiples", produces = { "application/json" })
@ResponseStatus(HttpStatus.CREATED)
@CrossOrigin(origins = "*") // 也可以加在方法級別
public EntityModel<Map<String, Object>> multiples() {
return EntityModel.of(overallMap);
}
}方法2:全局配置(推薦)
創(chuàng)建全局 CORS 配置類:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // 允許所有源
// 或者指定特定源:.allowedOrigins("http://localhost:3000", "http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(false) // 如果使用 allowCredentials(true),allowedOrigins 不能為 "*"
.maxAge(3600);
}
}方法3:使用 CorsFilter 過濾器
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 設置允許跨域請求的域名
config.addAllowedOrigin("*");
// 或者指定特定域名
// config.addAllowedOrigin("http://localhost:3000");
// 允許跨域請求頭
config.addAllowedHeader("*");
// 允許跨域請求方法
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("OPTIONS");
// 暴露哪些頭部信息
config.addExposedHeader("Authorization");
// 允許憑證
config.setAllowCredentials(true);
// 預檢請求的有效期,單位為秒
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}方法4:在 Spring Security 中配置 CORS
如果使用了 Spring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and() // 啟用 CORS
.csrf().disable() // 如果是 API 接口,通常禁用 CSRF
.authorizeRequests()
.antMatchers("/v1/multiples").permitAll()
.anyRequest().authenticated();
}
@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"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}方法5:如果遇到多個 CORS 頭部問題
如果出現(xiàn)兩個 access-control-allow-origin頭部,通常是因為多個地方都配置了 CORS??梢裕?/p>
檢查是否重復配置:確保只在一個地方配置 CORS
使用 @Order 注解:指定配置的優(yōu)先級
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsConfig implements WebMvcConfigurer {
// 配置
}檢查 Nginx/Apache 配置:如果前端有代理服務器,確保代理服務器沒有重復添加 CORS 頭部
最簡單的解決方案
對于快速測試,可以直接在控制器類上添加注解:
@RestController
@CrossOrigin(origins = "*")
public class PrintController {
// 你的代碼
}最佳實踐建議
- 開發(fā)環(huán)境:可以使用
*允許所有源 - 生產(chǎn)環(huán)境:應該指定具體的域名
- 如果有前端代理:可以考慮配置代理服務器處理 CORS
- 多個地方配置:確保不會在多個地方重復配置 CORS,否則會出現(xiàn)重復頭部
選擇最適合你項目需求的方案即可。通常方法1或方法2是最簡單的解決方案。
到此這篇關(guān)于SpringBoot中處理跨域資源的5種實現(xiàn)方法與對比的文章就介紹到這了,更多相關(guān)SpringBoot處理跨域資源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringSecurity中的UserDetails和UserDetailsService接口詳解
這篇文章主要介紹了SpringSecurity中的UserDetails和UserDetailsService接口詳解,UserDetailsService 在 Spring Security 中主要承擔查詢系統(tǒng)內(nèi)用戶、驗證密碼、封裝用戶信息和角色權(quán)限,需要的朋友可以參考下2023-11-11
SpringCloud-Gateway轉(zhuǎn)發(fā)WebSocket失敗問題及解決
這篇文章主要介紹了SpringCloud-Gateway轉(zhuǎn)發(fā)WebSocket失敗問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
Java實現(xiàn)遠程控制技術(shù)完整源代碼分享
這篇文章主要為大家詳細介紹了Java實現(xiàn)遠程控制技術(shù)完整源代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-08-08

