前后端分离时,获取不到session

  • Post author:
  • Post category:其他




前后端分离时,获取不到session


原文

在前后端分离的springboot项目中,进行图片验证时,第一次获取验证图片后,我将code值加密后存放到了session中,打算在下一个请求进行图片验证时直接从session中获取code值,然后进行对比。结果调试时,在第二步过程中获取的session一直为null。因此匹配结果一直false。当时后台代码如下:

controller层

@ApiOperation(value = "获取图片验证码", notes = "获取图片验证码")
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public void verfification(HttpServletRequest request, HttpServletResponse response, HttpSession session)throws IOException{
        // 设置响应的类型为图片格式
        response.setContentType("image/jpeg");
        // 禁止图片缓存
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        VerificationCode verificationCode = new VerificationCode();
        // 将验证码存入session
        session.setAttribute("verification", MD5.eccrypt(verificationCode.getCode().toLowerCase()));
        System.out.println(session.getId());
        verificationCode.write(response.getOutputStream());
    }

    @ApiOperation(value = "验证验证码是否正确", notes = "验证验证码是否正确")
    @ApiImplicitParam(name = "code",value = "图片验证码",required = true,dataType = "String")
    @RequestMapping(value = "/verification/{code}",method = RequestMethod.POST)
    public Response verfification(@PathVariable("code") String code,HttpSession session){
        System.out.println(session.getId());
        // 图片验证码
        if(!VerificationCode.isright(code.toLowerCase(),session)){
            return new Response("图片验证码错误!","图片验证码错误,请重新输入!");
        }
        return new Response(true,"图片验证码正确!","图片验证码成功!");
    }

拦截器:

@Configuration
public class CorsFilterConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // 允许跨域
        config.setAllowCredentials(true);
        // 设置允许跨域的域名,如:http://localhost:9004 如果为*号,则表示允许所有的
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

研究了大半个小时,才找到解决办法:后台代码没有问题,需要在前端代码每次发送请求时添加

axios.defaults.withCredentials = true

这段代码。

此时在后台两次请求获取的sessionId完全相同,也就是同一个session