Fork me on GitHub
如果对您有帮助,麻烦您点赞留言吧~~~

spring-session-data-redis导致跨域session失效

环境

前端:

  • vue全家桶
  • axios

后端:

  • springboot 2.1.9.RELEASE
  • spring-boot-starter-data-redis
  • spring-session-data-redis

根据以往的经验来看,无非就以下几种情况

设置跨域访问

  1. 前端设置携带cookie
	axios.get('http://xxxx/', {
		// 允许携带cookie
		withCredentials: true
	})
  1. 后端设置CORS
	response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
	response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
	response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
	response.setHeader("Access-Control-Max-Age", "3600");
	response.addHeader("Access-Control-Allow-Credentials", "true");

代理

设置vue.config.js

	module.exports = {
		publicPath: './',
		devServer: {
			proxy: {

				// 设置代理
				'/innerService': {
					target: 'http://192.168.30.248:8081',
					changeOrigin: true
				}
			}
		}
	

nginx

	location /innerService {
		proxy_pass   http://192.168.30.248:8081/;
		proxy_cookie_path / /;
		proxy_cookie_path / /;
		proxy_set_header   Host             $host;
		proxy_set_header   X-Real-IP        $remote_addr;
		proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
		proxy_set_header   X-Forwarded-Proto $scheme;
		index  index.html index.htm;
	}

这次的问题

但是这次,以前的方法都试过之后,还是无效,怀疑自己到底哪里写错了。
之后通过对比以前的项目,发现set-cookie里多了一个参数。
set-cookie: SESSION=ODdmZjM1ZDAtNTNkZS00YTJjLThkOTAtNDA5OWNjNzg4ZWY4; Path=/; HttpOnly; SameSite=Lax

没错,就是多了SameSite=Lax

于是就带着这个参数去搜索,

SameSite

Cookie 的SameSite属性用来限制第三方 Cookie,从而减少安全风险。也就是防止CSRF攻击
参考 http://www.ruanyifeng.com/blog/2019/09/cookie-samesite.html

解决方案

覆盖默认CookieSerializer

	@Bean
	public CookieSerializer httpSessionIdResolver(){
		DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();

		// 源码默认为Lax
		// private String sameSite = "Lax";
		cookieSerializer.setSameSite(null);
		return cookieSerializer;
    }
posted @ 2019-11-22 16:20  jarjune  阅读(1478)  评论(2编辑  收藏  举报