解决SpringSecurity跨域问题
报错信息
Access to XMLHttpRequest at 'http://localhost:8081/test/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
跨域问题指的是当一个网页的脚本向不同的域名(或者端口、协议)的服务器请求资源时,会被浏览器拦截。这是因为浏览器出于安全考虑,禁止跨域请求,以防止恶意网站窃取用户信息或者进行其他攻击行为。
此次在开发过程中因前后端分离的原因,使用了SpringSecurity框架,以前的跨域问题解决方案是,如下:
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
/**
* 处理跨域问题
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS")
.maxAge(3600);
}
}
但是这次不知道咋的,就是不行了,还说提示说跨域问题。报错结果图下:
在网上查了一下资料。
方法一:排除安全自动配置SecurityAutoConfiguration.class
在启动类的添加@SpringBootApplication注解添加exclude = {SecurityAutoConfiguration.class}。
如下:
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@MapperScan("com.javaandvue.mapper")
public class JavaVueDameApplication {
public static void main(String[] args) {
SpringApplication.run(JavaVueDameApplication.class, args);
}
}
响应结果:
方法二:配置Spring Security
在原来的配置文件之外,再建立一个SecurityConfig 。具体代码与注释如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 该方法用于配置应用程序的安全策略。
* 该代码用于启用跨域资源共享(CORS)功能。
* CORS是一种机制,允许Web浏览器从一个域向另一个域发出跨域请求。
* 调用 `http.cors()` 方法会在应用程序的HTTP响应中包含必要的CORS头,从而允许浏览器发出跨域请求。
* @param http HttpSecurity对象,用于配置应用程序的安全规则
* @throws Exception 配置过程中可能抛出的异常
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
http.cors();
}
}
这样即便不排除SecurityAutoConfiguration.class,也能完成跨域问题的处理。
PS:如果不知道如何选择,就编写两个配置类。一起加上
拓展
配置启用跨域资源共享
/**
* 该代码用于启用跨域资源共享(CORS)功能。
* CORS是一种机制,允许Web浏览器从一个域向另一个域发出跨域请求。
* 调用 `http.cors()` 方法会在应用程序的HTTP响应中包含必要的CORS头,从而允许浏览器发出跨域请求。
*/
/**
* 该代码的作用是允许所有来源的请求,
* 允许的方法包括GET、POST、OPTIONS、DELETE、PUT和PATCH,
* 允许的头部包括authorization、content-type和x-auth-token。
* 通过将该配置源注册到应用程序中,可以实现跨源资源共享。
* @return
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
// 创建一个新的CorsConfiguration对象
CorsConfiguration configuration = new CorsConfiguration();
// 设置允许的来源,"*"表示允许所有来源
configuration.setAllowedOrigins(Arrays.asList("*"));
// 设置允许的HTTP方法
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
// 设置允许的头部
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
// 创建一个新的UrlBasedCorsConfigurationSource对象
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 将CorsConfiguration对象注册到URL路径"/**",表示对所有路径生效
source.registerCorsConfiguration("/**", configuration);
// 返回配置好的CorsConfigurationSource对象
return source;
}
```