前后端分离时,获取不到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();<br>        // 允许跨域
        config.setAllowCredentials(true);<br>        // 设置允许跨域的域名,如: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

在做登录认证的时候,会出现请求未登录的情况,查看请求头的时候发现并没有把登录时的cookie设置到第二次的请求头里面。查看资料才知道跨域请求要想带上cookie,必须要在ajax请求里加上xhrFields: {withCredentials: true}, crossDomain: true。

解决思路
通过度娘查询发现必须在前后端配置一些东西,后端需在登录拦截器里增加一些响应头信息,前端需要在Ajax请求时增加一些参数。下面是具体的实现过程。

解决过程
登录拦截器

public class LogInterceptor implements HandlerInterceptor {
    @Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object object) throws Exception {
        
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    response.setHeader("Access-Control-Allow-Credentials","true");
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
    
    return true;
    }
}
注意:response.setHeader("Access-Control-Allow-Credentials","true"); 这是重点
response.setHeader("Access-Control-Allow-Origin", "*"); 这里不能写成("*")号
配置类

@Configuration
public class LoginConfig extends WebMvcConfigurerAdapter {
   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new LogInterceptor()).addPathPatterns("/login");
       super.addInterceptors(registry);
   }
}
这里拦截登录请求

修改前端请求
因为前端react使用的是axios,查看axios的文档发现默认配置里 withCredentials: false,withCredentials默认是false,意思就是不携带cookie信息,我们需要改成 true。
修改前端登录请求的js:
import axios from 'axios';
axios.defaults.withCredentials=true;

猜你喜欢

转载自blog.csdn.net/qq_29072049/article/details/83574221
今日推荐