问题的出现
由于没有携带Cookie,Spring Security 无法验证到登录状态,就需要重定向到登录页面,状态码是302
踩坑: localhost 与 127.0.0.1 也属于跨域,即使前端让ajax设置能够跨域
方法: 全部改成localhost就行
localhost 访问不跨域 但 127_0_0_1 访问跨域,你知道为什么吗
现象:
前后端设置,能够进行跨域携带cookie
后端Spring security
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true); // 允许携带cookie跨域
configuration.setAllowedOrigins(Arrays.asList(MessageConstant.LOGIN_SUCCESS_URL,MessageConstant.LOGIN_FRONT_URL)); // 允许所有域名进行跨域调用
configuration.setAllowedMethods(Collections.singletonList("*")); // 允许所有请求方法跨域调用
configuration.setAllowedHeaders(Collections.singletonList("*")); // 允许所有请求头跨域调用
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 对所有请求路径进行跨域设置
return source;
}
注入即可
//配置后端服务
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http
.headers().frameOptions().disable()// 解决 in a frame because it set 'X-Frame-Options' to 'deny' 问题 // 开启允许iframe 嵌套
.and()
.cors()//跨域
.configurationSource(corsConfigurationSource())
}
前端Ajax设置
新建Js文件 - ajax-config.js
// 超时时间是5秒
axios.defaults.timeout = 5000;
// 允许跨域
axios.defaults.withCredentials = true;
// Content-Type 响应头
axios.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded;charset=UTF-8";
// 基础url
axios.defaults.baseURL ='http://localhost:82';
// axios.defaults.baseURL = 线上生产环境地址;
需要发送ajax请求页面进行引入
<script src="../js/axios-0.18.0.js"></script>
<script type="text/javascript" src="../js/axios-config.js"></script>
注意这两个的引入顺序,不可颠倒
注意Live Server插件使用
Live Server默认启动在127.0.0.1,需要在设置里配置为localhost
引入Spring security后Spring boot跨域失效
Springboot 解决跨域问题的三种方式以及引入 SpringSecurity 跨域解决方案失效的情况
这里出现愿意关乎spring 拦截器(Interceptor)和过滤器(Filter)的执行顺序和区别
Spring Security 导致 Spring Boot 跨域失效问题
只要在Spring Secruity 配置跨域就行,详情查看Spring security的SSM配置以及Spring boot 配置