情景:
使用Vue和SpringBoot做前后端分离项目,出现跨域问题,因为前端访问调用后端3个接口,
第一:session校验 ,第二:登录 ,第三:查询接口
但是将session分别获取,然后打印出来,发现sessionid不一致,导致访问第三个查询数据接口而失败。
拦截器preHandle中加入如下 代码:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token
return true;
}
关键是这两句
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));//支持跨域请求
response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域
注意:当Access-Control-Allow-Credentials设置为ture时,Access-Control-Allow-Origin不能设置为*
package com.huayong.bi.web.interceptor;
import com.huayong.bi.inter.constants.EnumHttpStatusType;
import com.huayong.bi.inter.util.LogUtil;
import com.huayong.bi.web.common.util.SpringUtil;
import com.huayong.bi.web.dao.impl.PermissionCheckImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Set;
public class LoginInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
PermissionCheckImpl pci = null;
/**
* 进入controller层之前拦截请求
* @param request
* @param
* @param
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
PrintWriter out = null;
JSONObject jo = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// response.setHeader("Access-Control-Allow-Origin", "*");
// response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
// response.setHeader("Access-Control-Max-Age", "3600");
// response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token
//本地调试将if-else注释 直接返回true
if ("".equals((String) request.getSession().getAttribute("token")) || (String) request.getSession().getAttribute("token") == null) {
PrintWriter writer = response.getWriter();
writer.print("login");
return false;
} else {
System.out.println("=====LoginInterceptor=======");
//校验权限
String userName = (String) request.getSession().getAttribute("userName");
String mobile = (String) request.getSession().getAttribute("mobile");
LogUtil.print("---userName---" + userName);
LogUtil.print("---mobile---" + mobile);
LogUtil.print("URL : " + request.getRequestURL().toString());
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("RequestURI : " + request.getRequestURI());
pci = (PermissionCheckImpl) SpringUtil.getBean("permissionCheckImpl");
String uri = request.getRequestURI();
Set set = pci.queryPermissions(userName, mobile);
if(null==set || set.size()<1){
//默认用户
userName="普通用户";
mobile="0";
set = pci.queryPermissions(userName, mobile);
}
boolean per = false;
if (null != set && set.size() > 0) {
for (String se : set) {
LogUtil.print("---se---" + se);
if (uri.split("/")[1].equals(se.replace("/", ""))) {
if (per == false) {
per = true;
}
}
}
}else{
jo = new JSONObject();
jo.put("code", EnumHttpStatusType.no_permission.getCode());
jo.put("msg", EnumHttpStatusType.no_permission.getStatus());
jo.put("data", "");
out = response.getWriter();
out.append(jo.toString());
return false;
}
if (per == true) {
return true;
} else {
jo = new JSONObject();
jo.put("code", EnumHttpStatusType.no_permission.getCode());
jo.put("msg", EnumHttpStatusType.no_permission.getStatus());
jo.put("data", "");
out = response.getWriter();
out.append(jo.toString());
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
response.sendError(500);
return false;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//log.info("---------------视图渲染之后的操作-------------------------0");
}
}
前端使用 axios请求数据
axios默认是发送请求的时候不会带上cookie的,需要通过设置withCredentials: true来解决
axios.defaults.withCredentials = true
参考:
https://blog.csdn.net/xukongjing1/article/details/83308057