问题描述
前后端完全分离的项目,前端使用Vue + axios,后端使用SpringBoot。
使用CORS协议解决跨域访问数据限制的问题,但是发现客户端的Axios请求不会自动带上服务器返回的Cookie:JSESSIONID。
导致每一个Axios请求在服务端看来都是一个新的请求,都会在服务端创建新的Session(在响应消息头中设置Set-Cookie:JSESSIONID=xxx)。
分析原因
实际上,这是浏览器的同源策略导致的问题:不允许JS访问跨域的Cookie。
解决方案
需要从两方面进行解决问题
- 在配置中允许跨域请求Cookie
package com.xyl.Common;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author xianyanglin
* @title: CORSConfiguration
* @projectName login
* @description: 跨域配置
* @date 2019/6/22 002223:02
*/
@Configuration
public class CORSConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(false).maxAge(3600)
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
//设置允许跨域请求的域名
.allowedOrigins("*")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
- 2.客户端需要设置Ajax请求属性withCredentials=true,让Ajax请求都带上Cookie。在main.js中设置
axios.defaults.withCredentials = true