前后端跨域造成的session不同问题

前端和后端部署在同一服务器上的情况

今天测试前后端分离项目的时候,发现后端拿到的session id每次都不同,这样就导致我把验证码存在session里,而登录的时候却因拿不到正确的session,导致一直提示验证码输入错误。

尝试了网上的很多办法,比如ajax的xhrFields

  $.ajax({
      url: 'http://localhost:8081/captcha/generate?number=' + Math.random(),
      type: 'get',
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
      success: function (res) {
        console.log(res)
      }
    })

还有axios的axios.defaults.withCredentials = true

 axios.defaults.withCredentials = true
    axios({
      method: 'get',
      url: 'http://localhost:8081/captcha/generate?number=' + Math.random()
    }).then(function (res) {
      console.log(res)
    })

奇怪的是即使这两者配置后,后端拿到的session id还是不同,后端跨域配置如下 

package com.xidian.qunzhi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CorsConfig {
    public CorsConfig(){

    }

    @Bean
    public CorsFilter corsFilter(){
        //CorsFilter导.web.filter.CorsFilter下的
        //1.添加cors配置信息
        CorsConfiguration config=new CorsConfiguration();
        config.addAllowedOrigin("*");
        // 设置是否发送cookie信息
        config.setAllowCredentials(true);
        // 设置允许请求的方式  全部
        config.addAllowedMethod("*");
        // 设置允许的header
        config.addAllowedHeader("*");
        // 设置允许返回对象里面有自定义的header
        List<String> exposedHeaderList=new ArrayList<>();
        exposedHeaderList.add("sessionKey");
        config.setExposedHeaders(exposedHeaderList);

        //2. 为url添加映射路径 选第一个
        UrlBasedCorsConfigurationSource corsSource=new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**",config);

        //3. 返回中心定义好的corsSource
        return new CorsFilter(corsSource);
    }
}

历经磨难最后发现了问题,这是因为前端和后端的域名或者说ip地址不同导致的。我的前端启动在127.0.0.1:5500上,而我的后端默认是在localhost:8081上的,如果我将前端改为localhost:5500访问,所有问题就解决了 ,至此所有的session获取都相同了。

前后端部署在不同服务器上的情况

还有就是如果前端和后端真的部署在不同的服务器上,我们还有一招,但是必须保证后端的服务器配置了https证书。在java代码中处理response的时候加上下面这段代码,这样我们就可以通过后端给前端设置Cookie了

response.setHeader("Set-Cookie", "JSESSIONID=xxx;SameSite=None;Secure");

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值