223 字
1 分钟
SpringBoot3后端跨域处理
Springboot后端跨域处理
:::tip 问题背景
在例如Vue3+Springboot3前后端分离的项目中在未配置跨域拦截器的情况下前端直接访问后端接口则会直接报错。
:::
若没有使用SpringSecurity安全框架:
包目录下创建Config/CorsConfig.java
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//项目中的所有接口都支持跨域
.allowedOriginPatterns("*")//所有地址都可以访问,也可以配置具体地址
.allowCredentials(true)
.allowedMethods("*")//"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"
.maxAge(3600);// 跨域允许时间
}
}
若使用了SpringSecurity安全框架:
包目录下创建Config/CorsConfig.java
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("http://175.24.164.155")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
};
}
}
Config/SecurityConfiguration
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity,
PersistentTokenRepository repository) throws Exception {
return httpSecurity
.authorizeHttpRequests(conf ->
.csrf(AbstractHttpConfigurer::disable)
.cors(conf -> conf.configurationSource(this.corsConfigurationSource()))
.build();
}
private CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration cors = new CorsConfiguration();
cors.addAllowedOriginPattern("http://175.24.164.155");
cors.addAllowedOriginPattern("http://www.iloveu1314.xyz");
cors.addAllowedOriginPattern("http://localhost:5173");
cors.setAllowCredentials(true);
cors.addAllowedHeader("*");
cors.addAllowedMethod("*");
cors.addExposedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cors);
return source;
}