前後端分離時,獲取不到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;