前端请求报错情况:
java.lang.IllegalArgumentException: When allowCredentials is true,
allowedOrigins cannot contain the special value "*" since that cannot be set on the
"Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them expli
//前端请求发生跨域错误,加入@CrossOrigin(origins = "*",maxAge = 3600)注解
@CrossOrigin(origins = "*",maxAge = 3600)
正常Spring Boot项目的跨域问题在Controller中加入@CrossOrigin(origins = "*",maxAge = 3600)注解即可,origins = "*"允许所有域名,maxAge = 3600是最大响应时间。
如果Spring Boot项目中整合了Spring Security就需要再做一个配置类WebMvcConfig
/*
Security跨域问题配置文件
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");//允许任何域名
corsConfiguration.addAllowedHeader("*");//允许任何头
corsConfiguration.addAllowedMethod("*");//允许任何方法
corsConfiguration.addExposedHeader("Authorization");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
还需要将WebSecurityConfig中的configure方法中的http.csrf().disable();改成http.cors().and().csrf().disable();
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 如果有允许匿名的url,填在下面
// .antMatchers().permitAll()
.anyRequest().authenticated()
.and()
// 设置登陆页
.formLogin().loginPage("/login")
// 设置登陆成功页
.defaultSuccessUrl("/")
//登录失败页
.failureUrl("/login/error")
.permitAll()
// 自定义登陆用户名和密码参数,默认为username和password
// .usernameParameter("username")
// .passwordParameter("password")
.and()
.logout().permitAll();
// CSRF跨域
http.cors().and().csrf().disable();
}
整体项目目录如下: