在前后端分离的项目中Google浏览器中不能设置cookie,因为在Google浏览器80版本后增加了SameSite的cookie限制,默认为Lax模式不携带cookie和session。
解决这一问题的方法就是在正确配置springboot和vue的跨域配置的前提下做本地的域名映射,将本地的localhost地址映射成一个自定义的域名,不需要使用nginx做代理,直接通过访问域名进行联调测试。
(方案参考百度sso登录)
需要在后端设置cookie时指定上域名,并且前端的接口调用也要使用此域名才能正常设置cookie。
因为cookie设置成功的自然而然session也就可以用了。
springboot跨域配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: WangKangSheng
* @create: 2020-11-22 15:31
* 跨域配置
*/
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
/**
* Configure cross origin requests processing.
* @param registry CorsRegistry
*/
@Override public void addCorsMappings(CorsRegistry registry) {
System.out.println("跨域配置");
registry
.addMapping("/**") // 设置跨域的路径
.allowedOrigins("*") // 源头
.allowedMethods("*") // 方法
.allowCredentials(true) // session和cookie
.exposedHeaders("Access-Control-Allow-Origin",
"Access-Control-Allow-Credentials")
.maxAge(3600); // 请求的响应时间
}
}
前端vue中axios的配置代码
在main.js中设置可携带cookie和session。
import axios from 'axios'
axios.defaults.withCredentials=true;
效果:
一切正常。(前面两个域名是线上的和本地的localhost测试域名)