SpringBoot 前后端动静分离+集群 遇到的第一个问题:跨域session共享

关于跨域的文章  https://blog.csdn.net/freshlover/article/details/44223467

关于跨域cookie携带  https://blog.csdn.net/a317560315/article/details/78397369

CORS Filter文档  http://software.dzhuvinov.com/cors-filter-configuration.html

后台服务要实现高可用,需要做相关的配置改变,其中比较重要的问题是session共享

原项目中,使用了自定义token放在Request Header中来鉴定用户的身份

但前后端分离毕竟是使用了验证码,有跨域问题,还是需要cookie携带才能解决

但是要实现集群,就必须实现session共享

因为项目中正好在用了Redis,所以选择了Rdis缓存 + Spring Session来实现

maven依赖

<!--redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- spring session的依赖 --> 
<dependency> <groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId> 
</dependency>

redis连接参数

#redis

spring.redis.host=xx.xx.xx.xx

spring.redis.port=6379

spring.redis.password=xxxx

前端ajax全局设置

  xhrFields: {      

    withCredentials: true 

  }

后端SpringBoot
public class AuthApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                //全局支持CORS(跨源请求)
                registry.addMapping("/**")
                        //允许任意来源    
                        .allowedOrigins("*")
                        .allowedMethods("PUT", "DELETE","OPTIONS", "GET", "POST")
                        .allowedHeaders("*")
                        .exposedHeaders("access-control-allow-headers",
                                "access-control-allow-methods",
                                "access-control-allow-origin",
                                "access-control-max-age",
                                "X-Frame-Options")
                        .allowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS)//允许Cookie跨域
                        .maxAge(3600);
            }
        };
    }
}

此时,可以发送自定义的cookie信息了,但是没看到session被传送到服务器,

此时的情况时:
Response Headers
Set-Cookie:SESSION=4bbd2abd-4aa0-42d9-a8f4-d6b212a83b7e;path=/;Secure;HttpOnly
注意到了这后面的HttpOnly 不太明白其中的意思 查找如下文章中
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie

Secure 可选
一个带有安全属性的 cookie 只有在请求使用SSL和HTTPS协议的时候才会被发送到服务器。然而,保密或敏感信息永远不要在 HTTP cookie 中存储或传输,因为整个机制从本质上来说都是不安全的,比如前述协议并不意味着所有的信息都是经过加密的。
注意:非安全站点(http:)已经不能再在 cookie 中设置 secure 指令了(在Chrome 52+ and Firefox 52+ 中新引入的限制)。
HttpOnly 可选
设置了 HttpOnly 属性的 cookie 不能使用 JavaScript 经由  Document.cookie 属性、XMLHttpRequest 和  Request APIs 进行访问,以防范跨站脚本攻击(XSS)。

一开始尝试关闭掉这两个配置,但似乎没起作用,可能我参数用错了
等于要使用Https协议,由于测试的时候一直是使用http。。。哎!
因为项目早就使用了阿里云证书,开启了Https,所以此处略过
更换成Https协议后,每次发送的cookie中终于看到携带了session了(本地cookie中也看到了保存的session)

猜你喜欢

转载自blog.csdn.net/zx1323/article/details/79955168